简体   繁体   English

使用左侧联接的SELECT内有2个COUNT

[英]2 COUNT inside a SELECT with LEFT JOIN

I have 2 tables: 我有2张桌子:

user: 用户:

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

sends: 发送:

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

Every time a user sends a card (which goes by email) to another user, feeds the table. 每当用户向另一位用户发送卡片(通过电子邮件发送)时,该卡片就会被送入表格。

The question: I want to write a SELECT to know how many times the user was in ID_SEND and how many times the user was in ID_RECEIVE . 问题:我想编写一个SELECT来知道用户在ID_SEND次数以及用户在ID_RECEIVE中的ID_RECEIVE I tried something like this: 我尝试过这样的事情:

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

The problem is that both the ID_SEND and the ID_RECEIVE are returning the same value, the sum of the two ... where I am going wrong? 问题是ID_SENDID_RECEIVE都返回相同的值,即两个值的和……我要去哪里了?

LEFT JOIN twice, once for send, once for receive 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

Alternatively, single LEFT JOIN , conditional counting using case expressions: 或者,使用案例表达式,使用单个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

Try this. 尝试这个。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM