Hello i have two tables with a PK---->FK Relationship in InnoDB Engine---->MySQL&PHP
The Relationship is one---->many between first table which is 'Properties' and second
table which is 'propertyimages'. every row in first table is unique but in second table
every row of first table has got many rows in second table How can i **SELECT unique row from
first table and all info about first table from second table here is my query:
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
propertyimages.ImagePath
FROM properties
INNER JOIN propertyimages
ON properties.PropertyImageID=propertyimages.PropertyImageID
AND propertyimages.PropertyImageID=8;
it gives result:
PropertyName PropertyStatus Propertyid property Image Path
Appartment For Lease 8 upload/hydrangeas.jpg
Appartment For Lease 8 upload/jelsh.jpg
Appartment For Lease 8 upload/penguins.jpg
Appartment For Lease 8 upload/tulips.jpg
In this result the PropertyName and PropertyStatus is Repeated but i want a
unique as its stored in the first tableThe propertyName and PropertyStatus
belongs to first table.The Propertyid and PropertyImagepath belings to second table.
unfortunately a join will create a record for each element found in table 2 with a matching parent element (id 8) in the first table.
you could use a GROUP BY id 8 on the first table field, but you may not get all the results you want since it will take the first image only.
could you restructure your process so that when it comes to the images (and thier display) you could just run a single query to get every image related to property 8
you could always use a nested query (presuming you're looking to display images on a page for a property, etc)
$query1 = mysql_query("SELECT Propertyid, PropertyName, PropertyStatus FROM properties WHERE (search criteria)");
if (mysql_num_rows($query1) > 0) {
while ($q1Row = mysql_fetch_array($query1)) {
// Insert property specific data here before you display the images
echo $q1Row['PropertyName']."<br>\n";
echo $q1Row['PropertyStatus']."<br>\n";
$query2 = "SELECT PropertyImageID, ImagePath FROM propertyimages WHERE PropertyImageID='".$q1Row['Propertyid']."'"
if (mysql_num_rows($query2) > 0) {
while ($q2Row = mysql_fetch_array($query2)) {
// add code here to do whatever you want with the images
echo '<image src="'.$q2Row['ImagePath'].'"><br>\n';
}
}
}
}
}
it would also help to know your DB structure .. i'd imagine you'd want something like this
table 1 (properties)
PropertyID (Primary Key)
PropertyName
PropertyStatus
table 2 (propertyImages)
ImageID (Primary Key)
PropertyID (many to one reference to PropertyID in table 1)
ImagePath
I may be a bit oblivious to the FK method so if there is a lesson here for me as well, i'd love to hear what input you have.
you are one step away from the solution, you just need to select from second table and then for first so you will have all you result matched
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
propertyimages.ImagePath
FROM propertyimages
INNER JOIN properties
ON propertyimages.PropertyImageID = properties.PropertyImageID
AND propertyimages.PropertyImageID=8;
You could achieve this with GROUP_CONCAT. But I also think, it is better to make two queries. Nothing wrong with that.
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
GROUP_CONCAT(propertyimages.ImagePath)
FROM properties
INNER JOIN propertyimages
ON properties.PropertyImageID=propertyimages.PropertyImageID
AND propertyimages.PropertyImageID=8;
GROUP BY propertyimages.PropertyImageID
Related
Let's say I have the following table, called test:
Executing the query SELECT DISTINCT category FROM test ORDER BY category; will output:
When changing a value as follows:
…and calling the query SELECT DISTINCT category FROM test ORDER BY category; again, I'll get:
But I want to get the following instead:
Is there a way to do this in SQL? Or should I do this directly in my PHP?
You should have 3 tables here. One will hold the the categories, the other one will hold the items and the final one will hold the relations between categories and items (it is also known as associative table):
categories: id name
items: id name
categories_items: category_id item_id
Your query in this case will become:
SELECT id, name
FROM categories
ORDER BY name;
If you want to get all items from a category you could do:
SELECT id, name
FROM items
JOIN categories_items
ON items.id = categories_items.item_id
AND categories_items.category_id = 4;
You should definetely normalize your tables but if you still insist on this table structure, you can try this query:
WITH CatChar(aChar, remain) AS (
SELECT LEFT(category,1), RIGHT(category, LEN(category)-1)
FROM test WHERE LEN(category)>0
UNION ALL
SELECT LEFT(remain,1), RIGHT(remain, LEN(remain)-1) FROM CatChar
WHERE LEN(remain)>0
)
SELECT DISTINCT aChar FROM CatChar
(Assuming your all category names are just one char length, otherwise you should reorganeze LEFT(...) part to split according to your separator)
I have a while statement. That loops through my "customer" table and outputs the data.
while($row = mysql_fetch_array($result))
{
echo ".$row['category_id'].<br>
.$row['name'].<br>
.$row['address'].<br>
.$row['status'].<br>"
}
This all works fine.
The problem I have is the "category_id" is stored as a number in the "customer" table and the different categories are stored with their unique numbers and associated written names in a seperate "category" table.
For example customer table has,
category id - 150
name - Stackoverflow
address - 123 Main Street
status - Active
For example category table has
id - 150
name - Message Board
As I run my while loop to output the customer data, I need to query the category table to get and display the "name" associated to category_id.
I figured a while loop in a while loop, what do you guys think? I appreciate the help.
You'll want to do a MySQL join and get all the information at once: http://www.tizag.com/mysqlTutorial/mysqljoins.php
Your query will look something like this:
SELECT
c.name,
c.address,
c.status,
ca.name as category_name
FROM
customer c
JOIN
category ca
ON
ca.id = c.category_id
And your PHP will look like:
while($row = mysql_fetch_array($result)) {
echo "$row[category_name]<br>
$row[name]<br>
$row[address]<br>
$row['status']<br>";
}
I have an issue regarding PHP, MySql and foreign keys. I understand foreign keys and have a relationship between two tables in place as described:
Let's say I have 2 tables: 'vehicles' and 'manufacturers'.
Each row in the 'vehicles' table includes a manufacturerId column which is a foreign key relating to the 'manufacturers' table. This is set up nicely, in PhpMyAdmin when I insert a new row into the 'vehicles' table the manufacturerId column has a drop-down menu with the manufacturerId's listed as options. Very nice.
BUT: In my application, of course, I don't want the user to have to know (or have to guess) what the correct number for 'Ford' or 'BMW' is when they add a new vehicle, I want them to be able to choose the manufacturer by name.
But how does the application know the manufacturer names based on the manufacturerId? How does the application know there is a relationship between the 2 tables? Am I supposed to hard-code the relationship in the application? Am I supposed to modify all my queries to have a JOIN between the 2 tables? Or hard-code a query to get a list of manufacturers every time I want to display a drop-down of manufacturers?
Is there a way for the application to know about relationships between tables and be able to display data from a text column instead of the int column used as the ID?
Assuming your 2 table are structured like this:
VEHICLES
id
manufacturerId
vehicleName
MANUFACTURERS
id
manufacturerName
You would create your vehicle manufacturer select menu for users by querying the database like this:
// query the database
$q = 'SELECT id, manufacturerName FROM manufacturers';
$r = mysqli_query($link, $q);
// display a select menu using id and manufacturerName
echo '<select name="manufacturer">';
while($row = mysqli_fetch_assoc($r)) {
echo '<option value="'.$row['id'].'">'.$row['manufacturerName'].'</option>';
}
echo '</select>';
To use the post data from that menu to add a vehicle & manufacturer id to your vehicles table:
$q = "INSERT INTO vehicles (manufacturerId, vehicleName) VALUES ({$_POST['manufacturer']}, '{$_POST['vehicleName']}')";
mysqli_query($link, $q);
Finally, if you wish to select the vehicle name and manufacturer in the same query, you would join the tables like this:
// Select vehicle name and manufacturer for vehicle with id of 1
$q = "SELECT v.vehicleName, m.manufacturerName, v.id AS vehicleId, m.id AS manufacturerId
FROM vehicles AS v, manufacturers AS m
WHERE v.manufacturerID = m.id
AND v.id = 1";
mysqli_query($link, $q);
I think that should answer all your questions in one way or another!
I have 2 tables with the same columns.
for example
table 1
id
name
height
weight
table 2
id
name
height
weight
The data is table 2 is complete. But in table 1, only some data exists, and the rest of the columns are empty. for example:
table 1 table 2
id 4 4
name (empty) salman
height 5'11" 5'9"
weight (empyy) 65kg
I want a single script, that will allow me to update the table 2 with values from table 1, but only where it exists. In places where the table 1 is empty, I want to retain the data that already exists in table 2.
I've tried various ways, but all required multiple queries and are long and hectic. I want to know if there is a simpler way to get this done? Preferably in a single query?
Thank you
You can try by joining the 2 tables and then using the CASE keyword to conditionally update the fields:
UPDATE table2 t2 INNER JOIN table1 t1 USING (id)
SET
t2.name = CASE WHEN (t1.name IS NULL) THEN t2.name ELSE t1.name END
t2.height= CASE WHEN (t1.height IS NULL) THEN t2.height ELSE t1.height END
t2.weight = CASE WHEN (t1.weight IS NULL) THEN t2.weight ELSE t1.weight END
http://dev.mysql.com/doc/refman/5.5/en/case-statement.html
http://dev.mysql.com/doc/refman/5.5/en/update.html
What i want, to display rows from a table which is selected by a field from other table single value, lets say to display images from a table by last category id.
I have this type of query, but this return me all matching keys rows, if i inset LIMIT 1 then it return one row...
SELECT i.prof_image FROM profile_images i
JOIN images_cat cat ON (cat.cat_id = i.cat_id)
GROUP BY i.prof_image;
//OR LIMIT 1;
Any idea to fix this problem. (i.e. displaying the latest category images)?
This will work for your specific example.. If you need to be more selective, then please post some more details..
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
SELECT * FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.id
This query will grab all things in table_2 that have the same id value.
Note that it is a LEFT JOIN - which means that if there are no matching values in table_2, it will still return the values from table_1.
What is your intent with using last()?
Hope this helps.