我有这个查询要执行:
SELECT u1.firstname,
u1.lastname,
u1.totalcommission,
u1.userid,
count(DISTINCT u2.userid) AS level1,
count(DISTINCT u3.userid) AS level2
FROM users AS u1
INNER JOIN users AS u2 ON u1.userid = u2.affiliate1
AND u2.signupdate BETWEEN '2011-01-01 00:00:00' AND '2013-04-02 23:59:59'
LEFT JOIN users AS u3 ON u1.userid = u3.affiliate2
WHERE u1.usertypeid != '1'
GROUP BY u1.userid
ORDER BY count(DISTINCT u2.userid) DESC
表的索引:
PRIMARY BTREE Yes No userid 41318 A No
email BTREE Yes No email 41318 A No
affiliate1 BTREE No No affiliate1 1967 A Yes
affiliate2 BTREE No No affiliate2 258 A Yes
signupdate BTREE No No signupdate 41318 A No
查询有效,但问题是速度非常慢(表 users 有 43k 行,仅此而已),由于 count(distinct) 函数,它需要大约 10 秒。有没有办法用性能更好的东西代替它?
谢谢,
/卢卡