mysql中的数据库连接(从一个表中计数,从一个表中列出)

h43kikqp  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(362)

我有两张table,
用户
报表用户
在用户表中有以下列:,

userid , email , phone_number

报表用户表中有以下列:,

id , userid , report_user_id , reason

因此,我想获取具有report count的用户列表如果count为零,那么它必须为零。
用户表,

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\u user\u 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
bfnvny8b

bfnvny8b1#

我认为您在join语句中反转了user和report表:
您还应该添加 IFNULL 将0替换为空 COUNT 功能。

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

相关问题