减少mySQL查询和时间

时间:2012-07-22 21:30:55

标签: php mysql

我目前正致力于加速网站,即从查询中返回300,000多行。虽然我认为这不是DB服务器上的过多负载,但是这个查询是在while循环中发生的,具体取决于用户拥有的“库”数量。

例如,Joe在他的帐户中有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行,并在每个库中返回结果。在单个图库上运行的查询返回大约578ms的结果,但是对于许多图库,例如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

1 个答案:

答案 0 :(得分: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