从3.349s减少sql查询执行时间

时间:2017-10-25 18:09:46

标签: mysql query-performance

此查询工作正常,但使用3.3493执行,请帮我查看是否有办法更好地优化它。

SELECT u.ID, 
(SELECT meta_value FROM wpcg_usermeta WHERE meta_key = 'first_name' AND user_id = u.ID ) AS firstname, 
(SELECT meta_value FROM wpcg_usermeta WHERE meta_key = 'last_name' AND user_id = u.ID ) AS lastname, 
(SELECT meta_value FROM wpcg_usermeta WHERE meta_key = 'user_avatar_thumb' AND user_id = u.ID ) AS avatarurl, 
(SELECT COUNT(m.user_id) FROM wpcg_usermeta AS m , wpcg_users AS uz  WHERE m.user_id = uz.ID AND m.meta_key = 'user_parent' AND m.meta_value = u.ID AND u.user_registered BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()) AS referral_users 
FROM wpcg_users AS u 
WHERE (SELECT COUNT( user_id ) FROM wpcg_usermeta WHERE meta_key = 'user_parent' AND meta_value = u.ID ) > 0 
ORDER BY referral_users DESC LIMIT 15 OFFSET 0

2 个答案:

答案 0 :(得分:1)

考虑重组您的查询

Select col1, col2, col3, ...

FROM wpcg_users AS u 
JOIN wpcg_usermeta m on u.ID = m.user_id
where meta_key in ('first_name', 'last_name', ...)

您可以通过重新构建查询来消除许多子查询,从而提高性能。如果在select中有这样的子查询,则会为每一行运行。

答案 1 :(得分:0)

首先,提供使用过的表的元数据库和数据库的类型 - 列,索引,表的类型等(它看起来像MySql,但它可能是假的)。尝试在一些简单的请求上拆分此请求。然后尝试获取有关每个请求的统计信息。 还尝试减少对某些表的调用,执行嵌套的sql-c。 对不起我的英语不好。我现在正在研究它)