簡體   English   中英

加入MYSQL(從一張表計數並從一張表列出)

[英]Join in MYSQL (Count from One table and list from one table)

我有兩個桌子,

  • 用戶
  • 報告用戶

在“用戶表”中,有以下幾列,

userid , email , phone_number

在“報表用戶表”中,有以下幾列,

id , userid , report_user_id , reason

因此,如果計數為零,那么我想獲取具有報告計數的用戶列表,那么它必須為零。

用戶表,

userid | email         | phone_number
1      | abc@gmail.com | 12312312
2      | abcd@gmail.com | 112312312
3      | abc3@gmail.com | 112312312

報告用戶表,

id     |userid | report_user_id | phone_number
1      | 2     |   3            | 12312312
2      | 3     |   2            | 112312312
3      | 1     |   2            | 112312312

預期的輸出,

userid | email         | phone_number | report_count
1      | abc@gmail.com | 12312312     | 0
2      | abcd@gmail.com | 112312312   | 2
3      | abc3@gmail.com | 112312312   | 1

這里userid = 1的報告計數為零,因此必須為零(因為在report_user_id列中沒有條目1),userid = 2的報告計數為2,因此必須為2,而userid = 3的報告計數為1,因此必須為零。

我已經嘗試過該查詢,但無法獲得預期的結果,

SELECT count(LRU.report_user_id) as report_count FROM `lickr_report_user` as LRU LEFT JOIN lickr_users as LU ON LU.userid = LRU.report_user_id GROUP BY LU.userid

我認為喲顛倒了連接語句中的用戶和報告表:

您還應該在COUNT函數IFNULL替代0添加為null。

SELECT LU.userid, 
       LU.email, 
       LU.phone_number, 
       COUNT(IFNULL(LRU.report_user_id),0) as report_count 
FROM lickr_users as LU
LEFT JOIN `lickr_report_user` as LRU ON LU.userid = LRU.report_user_id 
GROUP BY LU.userid, LU.email, LU.phone_number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM