gpt4 book ai didi

php - MYSQL:不是在 while 循环中使用 SELECT 语句——我有什么选择?

转载 作者:行者123 更新时间:2023-11-29 01:12:26 24 4
gpt4 key购买 nike

我有一个包含类别列表的表格和另一个包含每个类别中的产品列表的表格。

例如

CatID | Cat_Name
----------------
1 | Books
2 | CDs

ProductID | Product_Name     | CatID
------------------------------------
1 |The Bible | 1
2 |The Koran | 1
3 |90s Greatest Hits | 2
4 |80s Greatest Hits | 2

我想做的就是得到

<ul>
<li>Books</li>
<ul>
<li>The Bible</li>
<li>The Koran</li>
</ul>
<li>Cds</li>
<ul>
<li>90s Greatest Hits </li>
<li>00s Greatest Hits </li>
</ul>
</ul>

不做(PHP)

$query = mysql_query("SELECT ... FROM categories")

while($row = mysql_fetch_assoc($query)):

$query2 = mysql_query("SELECT ... FROM products WHERE catId = $row['CatId'])

endwhile;

我如何摆脱使用嵌套的 while/SELECT 语句,我能否通过一个查询高效地完成它 - 我如何使用 PHP 访问相关数据?

编辑:我的印象是,如果您的表变得非常大,多个 SQL 查询会减慢您的页面,因此要优化页面加载,您应该尝试减少查询的数量?

最佳答案

使用 JOIN 选择所有产品和类别名称

select * from category c, products p where c.catID = p.catID order by p.catID

获取和分组结果

$products_by_cat = array();
foreach(fetch(....) as $record)
$products_by_cat[$record->catName][] = $record;

你会得到一个像这样的二维数组

 [books] => array(bible, koran)
[CDs] => array(cd1, cd2, ....)

用两个嵌套循环输出这个数组

 foreach($products_by_cat as $cat => $products)
<li> $cat <ul>
foreach($products as $p)
<li> $p->name </li>
</li></ul>

关于php - MYSQL:不是在 while 循环中使用 SELECT 语句——我有什么选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3423088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com