2016-03-09 59 views
0

我有2個表:2 COUNT內側留下了一個選擇加入

用戶:

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正在返回的值相同,則兩者之和......我要去的地方錯了嗎?

回答

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,使用CASE表達式條件計數:

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 
+0

2 LEFT JOIN我有一個錯誤:mysql_fetch_array()預計參數1是資源 – caiocafardo

+0

這是非常奇怪的......應該執行罰款。我會添加一個替代解決方案。請檢查5. – jarlh

+0

謝謝它的工作原理!我真的不知道wy與2左加入dindt作品.... – caiocafardo

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