2015-02-07 95 views
0

category table structureproduct table structure我有兩個表,一個是類別,另一個是products.Catid對於這兩個表都是很常見的。我需要使用兩個while循環來顯示錶中的數據。它的工作正常,但花費更多的時間,並拋出錯誤,如果它處理更多的類別。如何在php中優化mysql嵌套循環查詢

<table> 
<tr> 
<?php 
$cat=mysql_query("select * from category"); 
while($catquery=mysql_fetch_assoc($cat)) 
{?> 
<td><?php echo $catquery['catid'] ?></td> 
<td><?php echo $catquery['catname']?></td> 
<?php 
$catid=$catquery['catid']; 
}?> 
<?php 
$product=mysql_query("select * from product where catid=$catid"); 
while($productquery=mysql_fetch_assoc($product)) 
{ 
?> 
<td><?php echo $productquery['productname'] ?></td> 
</tr> 
</table> 
+0

你不能在查詢中使用聯接? – 2015-02-07 06:51:36

+0

如果我使用了內部連接,則爲每個產品名稱創建單獨的行。但我需要顯示所有產品的名稱在相應類別ID的單行中。 – 2015-02-07 06:53:13

+0

需要看到db結構 – 2015-02-07 06:57:34

回答

0
select * from category a left join product b 
on a.catid = b.catid 

更好逐個定義列,方便獲取數據到PHP,如:

select a.catid as category_catid, 
     a.catname as category_name, 
     b.productname as product_productname 
from category a left join product b 
on a.catid = b.catid 

如果你想顯示所有產品甚至catid已在類別被刪除,你可以使用此項(與FULL JOIN相同):

select a.catid as category_catid, 
     a.catname as category_name, 
     b.productname as product_productname 
from category a left join product b 
on a.catid = b.catid 
union 
select a.catid as category_catid, 
     a.catname as category_name, 
     b.productname as product_productname 
from category a right join product b 
on a.catid = b.catid 

這就是您如何獲取數據:

while($catquery=mysql_fetch_assoc($cat)) 
{?> 
<td><?php echo $catquery['category_catid'] ?></td> 
<td><?php echo $catquery['category_name']?></td> 
<td><?php echo $catquery['product_productname']?></td> 
.... 
+0

每個產品名稱都顯示在單個行的類別中。@Color Dalnet – 2015-02-07 09:15:45

+0

看起來像要打印類別一次? – 2015-02-07 09:27:39

+0

是的..與我的代碼我可以得到輸出,但由於嵌套while循環其大量數據的時間。 @顏色Dalnet – 2015-02-07 09:28:36

0

試試這個查詢。它將列出所有類別的詳細信息及其各自的產品名稱(catproducts - 在以下查詢中)。

<table> 

<?php 
$cat=mysql_query("select *,(select group_concat(productname) as catproducts from product where product.catid= category.catid) as catproducts from category"); 
while($catquery=mysql_fetch_assoc($cat)) { ?> 
    <tr> 
    <td><?php echo $catquery['catid']; ?></td> 
    <td><?php echo $catquery['catname'];?></td> 
    <td><?php echo $catquery['catproducts']; ?></td> 
    </tr> 
<?php }//end while ?> 

</table> 

所以你的輸出就會

catid catname  catproducts 

1  stationary book,pen 
2  leather  wallets,bags 
+0

可以請你簡單地用表格和while循環更新代碼.. @pritzzz – 2015-02-07 08:43:11

+0

檢查我編輯的答案 – Ruprit 2015-02-07 08:52:15

+0

catproducts顯示未定義的索引錯誤。它不工作.. @pritzzz – 2015-02-07 09:14:55