代码优化 - 删除嵌套的左连接

时间:2013-10-13 12:22:32

标签: mysql sql

为了提高查询效率,我希望能够消除嵌套的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)

有没有办法让这段代码更有效率?

1 个答案:

答案 0 :(得分:0)

如果grand_total不能为负数:

SELECT
    COUNT(DISTINCT users.id) AS NumCustomer,
    COUNT(distinct orders.userid) AS NumActiveCustomers,
    COUNT(distinct orders.userid)/COUNT(DISTINCT users.username) AS CloseRate
FROM users
LEFT JOIN orders ON orders.userid = users.id
WHERE users.datecreated LIKE '2013%' and grand_total>0
GROUP BY YEAR(users.created), MONTH(users.created)
ORDER BY YEAR(users.created), MONTH(users.created)

(如果它也不能为零,那么你不需要第二个where条件。)