【问题标题】:MySQL Joining three tables takes much time to executeMySQL加入三个表需要很长时间才能执行
【发布时间】:2021-04-15 11:42:21
【问题描述】:

连接三个表(产品、描述、图像)的以下选择查询需要 9 秒才能返回 10 行!

SELECT `products`.id, `products`.serialNumber, `products`.title, `descriptions`.description1, `descriptions`.description2, `descriptions`.description3, `descriptions`.description4,`products`.price,`products`.colors, `products`.category, `products`.available, `products`.status, GROUP_CONCAT(DISTINCT `images`.file_name ORDER BY `images`.id) AS images 
FROM `products` 
INNER JOIN `descriptions`
ON `products`.id = `descriptions`.product_id 
LEFT JOIN `images` 
ON `products`.id = `images`.product_id
WHERE `products`.status = 1 
GROUP BY `products`.id
ORDER BY `products`.id DESC
LIMIT 10;

所以经过一些研究,我得到了下面的答案,其中包含连接两个表并且只需一秒钟即可返回 10 行,我如何添加第三个表(描述)?谢谢

SELECT  *,
    ( SELECT  group_concat(`images`.file_name)
        FROM  `images`
    ) AS images
FROM  `products`
JOIN  `images` ON `products`.id = `images`.product_id
WHERE `products`.status = 1 
GROUP BY `products`.id
ORDER BY `products`.id DESC
LIMIT 10 

【问题讨论】:

  • 发布性能问题时,您应该提供表格定义、数量和解释计划。在大多数情况下,性能不佳是由于索引不佳(或没有索引),因此需要表定义和解释计划。时间对于卷来说可能是合理的,顺便说一句,限制是对结果集的限制而不是读取限制..
  • 是的,但是经过一些研究,我发现我的查询中的问题..为此我只发布了查询...正确的答案确实将执行时间从 8 秒减少到 1第二个!

标签: mysql sql json join left-join


【解决方案1】:

为了获得更好的性能,请确保您在表产品列上有一个复合索引

status, id 

关于表的描述和列的索引

product_id 

在表格图像上的列索引

 product_id 

无论如何,您都可以使用子查询来加入 3 个表以进行聚合并加入此子查询

    SELECT  *, my_images.aggr_images
    FROM  `products`
    INNER JOIN `descriptions` ON `products`.id = `descriptions`.product_id 
    LEFT JOIN ( SELECT product_id, group_concat(`images`.file_name) aggr_images 
            FROM  `images`
            GROUP BY product_id
        ) AS my_images on my_images.product_id = `products`.id
    WHERE `products`.status = 1 
    ORDER BY `products`.id DESC
    LIMIT 10 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2011-03-14
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多