[英]Select all result from first table without matching with second table
I have 2 tables one is user table and another is rating table which have the mapping data of user rating 我有2个表,一个是用户表,另一个是评分表,其中包含用户评分的映射数据
user table 用户表
user_id | firstname | lastname
--------------------------------
1 | 1test | 1test lname
2 | 2test | 2test lname
3 | 3test | 3test lname
4 | 4test | 4test lname
5 | 5test | 5test lname
rating table 评分表
user_id | rating
------------------
1 | 4
2 | 3
3 | 5
1 | 4
In result i need avg value of rating with user info in one query 结果,我需要在一个查询中提供用户信息的平均评级值
user_id | firstname | lastname | rating
---------------------------------------------
1 | 1test | 1test lname | 4
2 | 2test | 2test lname | 3
3 | 3test | 3test lname | 5
4 | 4test | 4test lname | 0
5 | 5test | 5test lname | 0
Here is your query, 这是您的查询,
SELECT ut.*,AVG(rt.rating)as rating
FROM user_table ut
INNER JOIN rating_table rt ON ut.user_id = rt.user_id
This is query you can use this to find average of all rating of all user 这是查询,您可以使用它来查找所有用户的所有评分的平均值
SELECT u.*, IFNULL(AVG(rating),0) as rating
FROM user u
LEFT JOIN rating r
ON u.user_id = r.user_id
GROUP BY r.user_id;
Use LEFT JOIN to fetch all records from user table and matching records from rating table. 使用LEFT JOIN从用户表中获取所有记录,从评分表中获取匹配的记录。
Try this: 尝试这个:
SELECT u.user_id,
u.firstname,
u.lastname,
AVG(IFNULL(r.rating, 0)) AS rating
FROM `user` u
LEFT OUTER JOIN rating r ON u.user_id = r.user_id
GROUP BY u.user_id, u.firstname, u.lastname;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.