Reputation: 43
I have 2 tables one is user table and another is rating table which have the mapping data of user rating
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
Upvotes: 2
Views: 53
Reputation: 29051
Use LEFT JOIN to fetch all records from user table and matching records from rating table.
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;
Upvotes: 1
Reputation: 3756
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;
Upvotes: 1
Reputation: 1583
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
Upvotes: 1