您好,我正在制作一个 T 恤网上商店网站。每个产品(总共 1400 个)都有自己的 ID (idedro),但每个 ID 都有不同的颜色,有时是一种,有时是 20 种。 我需要在自己的图片中显示每个产品及其下面的所有颜色,但我认为循环内的循环占用了太多的 CPU 时间。有没有办法用一个循环来实现它或 enter image description here与 JOIN 或准备好的语句一起使用吗?
$querycount = mysqli_query($link,"SELECT DISTINCT (idedro)
FROM megadb WHERE catteniskiipotnici=1 ORDER BY idedro ASC");
while ($rowcounts = mysqli_fetch_assoc($querycount)) {
$result1 = mysqli_query($link,"SELECT color
FROM megadb WHERE idedro='$rowcounts[idedro]'");
while ($row1=mysqli_fetch_array($result1)) { echo $row1[color]; }
}
最佳答案
这应该可以使用 GROUP_CONCAT()
完成您想要的操作:
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
MySQL 5.6 架构设置:
CREATE TABLE megadb
(`idedro` int, `color` varchar(5), `catteniskiipotnici` int)
;
INSERT INTO megadb
(`idedro`, `color`, `catteniskiipotnici`)
VALUES
(1, 'blue', 1),
(2, 'blue', 1),
(2, 'red', 1),
(3, 'blue', 1),
(3, 'red', 1),
(3, 'white', 1),
(4, 'blue', 0)
;
查询 1:
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
<强> Results :
| idedro | group_concat(color) |
|--------|---------------------|
| 1 | blue |
| 2 | blue,red |
| 3 | blue,red,white |
关于php - 如何在没有嵌套循环的情况下使 SELECT 更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632011/