对两个由不同外键

时间:2015-05-05 09:34:58

标签: mysql sql join

我们假设我有两张桌子:

Users
id: integer
name: string

Messages
id: integer
sender_id: integer
receiver_id: integer
body: string

我需要获取所有用户的已发送和已接收消息的统计信息。

对于已发送的邮件,我的查询按预期工作:

SELECT users.id, COUNT(*) total_sent 
FROM users 
LEFT OUTER JOIN messages sent_messages ON sent_messages.sender_id = users.id
GROUP BY users.id;

+----+------------+
| id | total_sent |
+----+------------+
|  1 |          3 |
|  2 |          2 |
|  3 |          1 |
+----+------------+

但是我需要扩展查询并同时获取已接收消息的数量。我的尝试是:

SELECT users.id, COUNT(sent_messages.id) total_sent, COUNT(received_messages.id) total_received
FROM users 
LEFT OUTER JOIN messages sent_messages ON sent_messages.sender_id = users.id
LEFT OUTER JOIN messages received_messages ON received_messages.receiver_id = users.id
GROUP BY users.id;

不幸的是,它会产生错误的结果。

1 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助:

select u.id, r.total_received, s.total_sent from users as u left outer join (select count(id) as total_received, receiver_id from Messages group by receiver_id ) as r on r.receiver_id =u.id left outer join (select count(id) as total_sent, sender_id from Messages group by sender_id) as s on sender_id=u.id