I have the following tables: Suppliers:
Id Name
1 Dan
2 John
Products:
Id Name C_Id
1 AAA 1
2 BBB 2
3 CCC 1
What I want to do is iterating over each supplier (once), and print it's products. Something like that:
{c.name} supllies {p.id} {p.name}
Dan supplies 1 AAA and 3 CCC
John supplies 2 BBB
What would be right way to fetch this data from the server? because now I use 2 loops, and I think there should be an more efficient way.
while ($row = mysql_fetch_array(mysql_query("SELECT Id,Name FROM Suppliers")))
$id = $row["id"];
while ($row2 = mysql_fetch_array(mysql_query("SELECT Id,Name FROM Products WHERE C_Id = $id")))
push each $row2 in $array
print $array for each $row1
Thank you
您可以使用join:
SELECT Suppliers.Id S_ID, Suppliers.Name S_NAME, Products.Id P_ID, Products.Name P_NAME FROM Suppliers LEFT JOIN Products ON Suppliers.Id = Products.C_Id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.