2015-02-07 121 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