php - 如何在没有嵌套循环的情况下使 SELECT 更快

标签 php mysql sql loops nested

您好,我正在制作一个 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

SQL Fiddle

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/

相关文章:

java - 如何切换现有数据源的数据库上下文?

Php搜索字符串(带通配符)

php - 如何在脚本仍在执行时设置任何数据?

mysql - 使用查询中的函数或设置作为变量是否存在速度差异?

mysql - 这个子查询是如何工作的?

sql - 删除临时表(如果存在)

php - 如果网站关闭,则返回并终止 session

java - 使用 PHP OpenSSL 将 Java AES/ECB/PKCS7Padding/代码转换为 PHP

python - 将查询结果附加到 PostgreSQL 中的同一结果行 - Redshift

mysql - SUM 后在 SQL 查询中查找 AVG 值 - 组函数的使用无效