为了使这个查询更有效率,我希望可以消除嵌套的LEFT JOIN
. 我考虑过是否可以替换COUNT(ActiveUsers)
为COUNT(DISTINCT IF(SUM(grand_total)>0,id,NULL))
以便我可以删除LEFT JOIN
,但这似乎没有得到正确的结果。这是我正在使用的原始代码:
SELECT
COUNT(DISTINCT users.id) AS NumCustomer,
COUNT(ActiveUsers) AS NumActiveCustomers,
COUNT(ActiveUsers)/COUNT(DISTINCT username) AS CloseRate
FROM users
LEFT JOIN orders ON orders.userid = users.id
LEFT JOIN (SELECT id AS ActiveUsers FROM users LEFT JOIN orders ON orders.userid = users.id GROUP BY id HAVING SUM(grand_total)>0 ) AS Active ON users.id = Active.ActiveUsers
WHERE users.datecreated LIKE '2013%'
GROUP BY YEAR(users.created), MONTH(users.created)
ORDER BY YEAR(users.created), MONTH(users.created)
有没有办法让这段代码更有效率?