我有一个在使用 DISTINCT 时有效的查询。但是我有一种感觉,我可以以一种有助于我避免使用 DISTINCT 的方式重写查询,这将使数据库更容易(更快)处理查询。
如果重写查询没有意义,请解释一下,如果有,请查看简化查询并提示我如何重新编写它,这样我就不会首先得到重复。
SELECT Us.user_id, COUNT( DISTINCT Or.order_id ) AS orders
FROM users AS Us
LEFT JOIN events AS Ev ON Ev.user_id = Us.user_id
LEFT JOIN orders AS Or ON Or.event_id = Ev.event_id
OR Or.user_id = Us.user_id
GROUP BY Us.user_id
查询的简短描述:我有一张用户表,其中包含他们的事件和订单。有时订单有列 user_id,但大多数情况下它是空的,它们必须通过事件表连接。
编辑:
这些是我编写的简化查询的结果,首先没有 distinct,然后包括 distinct。
user_id orders
3952 263
3953 7
3954 2
3955 6
3956 1
3957 0
...
user_id orders
3952 79
3953 7
3954 2
3955 6
3956 1
3957 0
...
问题已解决:
SELECT COALESCE( Or.user_id, Ev.user_id ) AS user, COUNT( Or.order_id ) AS orders
FROM orders AS Or
LEFT JOIN events AS Ev ON Ev.event_id = Or.event_id
GROUP BY COALESCE( Or.user_id, Ev.user_id )