如何在php中优化嵌套循环的mysql查询

时间:2015-02-07 06:50:58

标签: php mysql while-loop

category table structure product table structure我有两个表,一个是category,另一个是products.Catid对于两个表都很常见。我需要使用两个while循环来显示表中的数据。它的工作正常,但如果处理更多类别,则会花费更多时间并抛出错误。

   <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>

2 个答案:

答案 0 :(得分: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>
....

答案 1 :(得分: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
相关问题