[英]Join in MYSQL (Count from One table and list from one table)
I have two table, 我有两个桌子,
In User Table there are following columns, 在“用户表”中,有以下几列,
userid , email , phone_number
In Report User Table there are following columns, 在“报表用户表”中,有以下几列,
id , userid , report_user_id , reason
So, I want to fetch the list of user with report count if count is zero then it must be with zero. 因此,如果计数为零,那么我想获取具有报告计数的用户列表,那么它必须为零。
User Table, 用户表,
userid | email | phone_number
1 | abc@gmail.com | 12312312
2 | abcd@gmail.com | 112312312
3 | abc3@gmail.com | 112312312
Report User Table, 报告用户表,
id |userid | report_user_id | phone_number
1 | 2 | 3 | 12312312
2 | 3 | 2 | 112312312
3 | 1 | 2 | 112312312
Expected OutPut, 预期的输出,
userid | email | phone_number | report_count
1 | abc@gmail.com | 12312312 | 0
2 | abcd@gmail.com | 112312312 | 2
3 | abc3@gmail.com | 112312312 | 1
Here userid = 1 has zero report count so it must be zero (because in report_user_id column there is no entry of 1) , userid = 2 has 2 report count so it must be 2 , and userid = 3 has 1 report count so it must be zero. 这里userid = 1的报告计数为零,因此必须为零(因为在report_user_id列中没有条目1),userid = 2的报告计数为2,因此必须为2,而userid = 3的报告计数为1,因此必须为零。
I have tried this query but I'm not able to get the expected result, 我已经尝试过该查询,但无法获得预期的结果,
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
I think yo reversed the user and report table in the join statement: 我认为哟颠倒了连接语句中的用户和报告表:
You should also add an IFNULL
substitute 0 to null in COUNT
function. 您还应该在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.