我正在执行此查询,结果很好,但问题是它花了太长时间,有人可以告诉我如何使这个效率高(SQL显示这个查询需要2.8秒,但实际上它需要超过10秒)一开始我在3张桌子上使用连接,但是查询花费的时间比这个更长。 提前致谢。
SELECT
ee_expert.expert_id ,
AVG( ee_expert_rating.rating_stars ) AS total_rating,
ee_expert.expert_id,
COUNT( DISTINCT ee_expert_rating.rating_id ) AS rating_count
FROM
ee_expert_rating
RIGHT JOIN ee_expert
ON ee_expert.expert_id = ee_expert_rating.expert_id
WHERE
expert_verified_email =2
AND expert_brief_description != ''
AND expert_account_status =1
AND ee_expert.expert_id IN
(
SELECT
expert_id
FROM
ee_expert_categories
WHERE
ee_expert_categories.category_id =5
GROUP BY
expert_id
)
GROUP BY
ee_expert.expert_id
ORDER BY
rating_count DESC
答案 0 :(得分:1)
这应该快一点:(删除了内联组,在这种情况下使用exists可以提供帮助。)
SELECT
ee_expert.expert_id ,
AVG( ee_expert_rating.rating_stars ) AS total_rating,
COUNT( DISTINCT ee_expert_rating.rating_id ) AS rating_count
FROM
ee_expert_rating RIGHT JOIN
ee_expert ON ee_expert.expert_id = ee_expert_rating.expert_id
WHERE
expert_verified_email =2 AND
expert_brief_description != '' AND
expert_account_status =1 AND
exists(
SELECT
expert_id
FROM
ee_expert_categories
WHERE
ee_expert_categories.category_id =5 and
ee_expert_categories.expert_id=ee_expert.expert_id
)
GROUP BY
ee_expert.expert_id
ORDER BY
rating_count DESC
(尝试保持IN也/没有内部组。)
答案 1 :(得分:1)
有两件事让整个事情变得缓慢:
需要10秒,因为通过网络传输数据,并以HTML格式显示(phpMyAdmin?),它比实际语句慢。这只是猜测,但在98%的情况下都是如此。
在IN()
中使用subselect总是很慢(我想因为它是针对每个父数据集递归运行的)。一个选项是使用EXISTS()