繁体   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