使用LEFT JOIN在SELECT内部进行2 COUNT

时间:2016-03-09 20:28:40

标签: mysql select sum left-join

我有两张桌子:

用户:

ID | NAME 
1  | caio 
2  | mike
3  | peter

发送:

ID | ID_SEND | ID_RECEIVE
1  |    1    |     2
2  |    2    |     3
3  |    3    |     2
4  |    2    |     1

每次用户将卡(通过电子邮件发送)发送给其他用户时,都会提供表格。

问题:我想写一个SELECT来了解用户在ID_SEND中的次数以及用户在ID_RECEIVE中的次数。我试过这样的事情:

SELECT 
    user.email, 
    COUNT(sends.id_receive) AS numberReceive, 
    COUNT(sends.id_send) AS numberSend
FROM
    user
LEFT JOIN 
    sends ON user.id = sends.id_send OR user.id = sends.id_receive
GROUP BY 
    user.email

问题是ID_SENDID_RECEIVE都返回相同的值,两者的总和......我哪里出错?

2 个答案:

答案 0 :(得分:0)

LEFT JOIN两次,一次发送,一次接收

SELECT u.email,
       COUNT(r.id_receive) AS numberReceive,
       COUNT(s.id_send) AS numberSend
FROM user u
LEFT JOIN sends r ON u.id = r.id_receive
LEFT JOIN sends s ON u.id = s.id_send
GROUP BY u.email

或者,单LEFT JOIN,使用案例表达式进行条件计数:

SELECT u.email,
       SUM(case when u.id = s.id_receive then 1 else 0 end) AS numberReceive,
       SUM(case when u.id = s.id_send then 1 else 0 end) AS numberSend
FROM user u
LEFT JOIN sends s ON u.id IN (s.id_receive, s.id_send) 
GROUP BY u.email

答案 1 :(得分:0)

试试这个。

SELECT S.*, 
   R.received 
FROM   (SELECT u.NAME, 
           Count(snd.id) sends 
    FROM   USER u 
           JOIN sends snd 
             ON snd.id_send = u.id 
    GROUP  BY u.NAME) S 
   LEFT JOIN (SELECT u.NAME, 
                     Count(rec.id) received 
              FROM   USER u 
                     JOIN sends rec 
                       ON rec.id_receive = u.id 
              GROUP  BY u.NAME) R 
          ON S.NAME = R.NAME