Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 减少mySQL查询和时间_Php_Mysql - Fatal编程技术网

Php 减少mySQL查询和时间

Php 减少mySQL查询和时间,php,mysql,Php,Mysql,我目前正在加快一个网站的速度,这是从一个查询返回300000多行。虽然我不认为DB服务器上的负载太大,但根据用户拥有的“库”数量,这个查询是在While循环中进行的 例如,乔的帐户中有10个画廊。每个图库都有x个图像,这些图像上有x个评论。因此当前正在运行的查询 SELECT count(*) as total FROM galleryimage a INNER JOIN imagecomments b ON a.id=b.imgId WHERE a.galleryId='".$row['

我目前正在加快一个网站的速度,这是从一个查询返回300000多行。虽然我不认为DB服务器上的负载太大,但根据用户拥有的“库”数量,这个查询是在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 <> ''

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

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

在创建查询时,您是否拥有所有库ID?@AlexandreP.Levasseur-是的,我有-更新的问题您说您不能更改架构,但可以添加表吗?是的,添加表是一种可能性…首先,如果您在创建查询时拥有所有的ID,您可以将WHERE子句修改为a.galleryId所在的类型。。。你在哪里替换。。。使用您拥有的ID,用逗号分隔。此外,如果您可以索引galleryId,则检索过程会快得多。
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