[英]Left Join Returning Only One Record
I want to join two tables.我想加入两张桌子。 One is 'users' and the other is 'reviews'.
一个是“用户”,另一个是“评论”。 What i want to achieve is all the users with their average and total ratings from reviews table.
我想要实现的是所有用户的平均评分和总评分来自评论表。 I get the desired result when the review table has the ratings for all the users.
当评论表包含所有用户的评分时,我得到了预期的结果。 But when the reviews table is empty, i get only one record from users table.
但是当评论表为空时,我只能从用户表中获得一条记录。 Currently there are 3 users in users table but the query is showing only one record.
目前 users 表中有 3 个用户,但查询只显示一条记录。
I want to get all the users even when there is no record of a user in reviews table.即使评论表中没有用户记录,我也想获得所有用户。 Here is the query i am using
这是我正在使用的查询
SELECT u.id, u.name, u.photo, COUNT(r.rating) AS totalratings,
( SELECT ROUND (AVG(r.rating),0)
FROM reviews r
WHERE r.fk_receiver_id = u.id) AS avg_rating
FROM
users u LEFT JOIN reviews r
ON r.fk_receiver_id = u.id
WHERE u.role=2
GROUP BY r.fk_receiver_id
You are grouping by the wrong column;您按错误的列分组; when it's null (it will be because of the left join) the grouping won't behave as you want.
当它是 null (这将是因为左连接)时,分组不会像你想要的那样运行。 Your query sould look like:
您的查询看起来像:
SELECT
u.id,
max(u.name) as name,
max(u.photo) as photo,
COUNT(r.rating) AS totalratings,
ROUND(AVG(r.rating), 0) AS avg_rating
FROM users u
LEFT JOIN reviews r ON r.fk_receiver_id = u.id
WHERE u.role = 2
GROUP BY u.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.