0

我目前正在加快网站的速度,该网站从查询中返回 300,000 多行。虽然我认为这不会对数据库服务器造成太大的负载,但此查询是在 while 循环中发生的,具体取决于用户拥有的“画廊”的数量。

例如,乔的帐户中有 10 个画廊。这些画廊中的每一个都有 x 数量的图像,这些图像有 x 数量的评论。所以当前正在运行的查询......

SELECT count(*) as total 
FROM galleryimage a 
INNER JOIN imagecomments b ON a.id=b.imgId 
WHERE a.galleryId='".$row['id']."' 
AND b.note <> ''

...正在查看所有 galleryimage 表 334,000 行和 imagecomments 表 76,000 行,并在每个图库上返回结果。在单个画廊上运行的查询在大约 578 毫秒内返回结果,但是对于许多画廊,比如 30-40,您可能会看到 17 秒以上的页面加载时间。有关如何处理此问题的任何建议?

我无法更改数据库架构....

查询画廊 id

SELECT a.id, 
       a.created, 
       a.name, 
       b.clientName, 
       a.isFeatured, 
       a.views, 
       a.clientId 
FROM gallery a 
INNER JOIN client b 
ON a.clientId = b.id 
WHERE a.isTemp = 0 
AND a.clientRef = '{$clientRef}' 
AND a.finish='1'  
AND a.isArchive='0' 
ORDER BY created 
DESC
4

1 回答 1

2

您可以合并查询并消除循环的需要:

SELECT 
    a.id, 
    a.created, 
    a.name, 
    b.clientName, 
    a.isFeatured, 
    a.views, 
    a.clientId,
    COALESCE(c.img_cnt, 0) AS gallery_image_count,
    COALESCE(c.comment_cnt, 0) AS gallery_comment_count
FROM 
    gallery a 
INNER JOIN 
    client b ON a.clientId = b.id 
LEFT JOIN
(
    SELECT aa.galleryId, 
           COUNT(DISTINCT aa.id) AS img_cnt, 
           COUNT(1) AS comment_cnt
    FROM galleryimage aa
    INNER JOIN imagecomments bb ON aa.id = bb.imgId
    WHERE bb.note <> ''
    GROUP BY aa.galleryId
) c ON a.id = c.galleryId
WHERE 
    a.isTemp = 0 AND
    a.clientRef = '{$clientRef}' AND
    a.finish = 1 AND
    a.isArchive = 0 
ORDER BY 
    a.created DESC
于 2012-07-22T22:01:41.330 回答