SQL JOIN平均值

时间:2015-05-04 16:49:18

标签: mysql sql-server performance optimization query-optimization

我需要一些帮助来优化我的查询

我有两张桌子

表1 - users_location; 表2 - users_rating

+-------+---------+      +-------+--------+
|user   | location|      | user  | rating | 
+-------+---------+      +-------+--------+
| user1 |   AA    |      | user1 |   1    |
| user2 |   BB    |      | user1 |   3    |
| user3 |   CC    |      | user1 |   4    |
| user4 |   AA    |      | user2 |   3    |
| user5 |   BB    |      | user4 |   2    |
| user6 |   CC    |      | user4 |   4    |

我需要按位置选择用户及其平均评分(例如AA)。 现在我的查询是:

SELECT * 
FROM users_loaction AS TABLE1
LEFT JOIN (
    SELECT  
        user, 
        AVG(rating) 
    FROM users_rating group by user
) AS TABLE2 
ON  TABLE1.user = TABLE2.user
WHERE TABLE1.location = AA

我认为SQL会计算所有用户的平均评分,然后只加入我需要的,这不是优化的。

3 个答案:

答案 0 :(得分:1)

对于mysql,你可以试试这个:

SELECT *, 
    (SELECT AVG(rating) FROM users_rating AS ur WHERE ur.user = ul.user ) AS rating
FROM users_location AS ul
WHERE ul.location = 'AA';

这是sqlfiddle

答案 1 :(得分:0)

http://sqlfiddle.com/#!9/c34c8d/1

SELECT t.*, AVG(t2.rating) 
FROM users_location t
LEFT JOIN  users_rating t2
ON  t.user = t2.user 
WHERE t.location = 'AA'
GROUP BY t.Location;

SELECT t.*, AVG(t2.rating) 
FROM users_location t
LEFT JOIN  users_rating t2
ON  t.user = t2.user 
WHERE t.location = 'AA'
GROUP BY t.user;

SELECT t.*, AVG(t2.rating) 
FROM users_location t
LEFT JOIN  users_rating t2
ON  t.user = t2.user 
WHERE t.location = 'AA'
GROUP BY t.Location, t.user

答案 2 :(得分:0)

根据Rick的反馈,下面是MySQL和SQL Server的答案:

<强>的MySQL

http://sqlfiddle.com/#!9/9e9be8/1

SELECT l.user, AVG(r.rating) FROM users_location l
    LEFT JOIN users_rating r ON l.user = r.user
    WHERE l.location = 'AA'
    GROUP BY l.user

SQL Server

http://sqlfiddle.com/#!6/379e6/1

SELECT l.[user], AVG(r.rating) FROM users_location l
    LEFT JOIN users_rating r ON l.[user] = r.[user]
    WHERE l.location = 'AA'
    GROUP BY l.[user]