0

我需要一些幫助我查詢的優化SQL JOIN平均值

我有兩個表

表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將所有用戶計算平均得分,然後加入只是我所需要的,這不是最優化。

回答

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

+0

謝謝你,你的決定非常好 – AlexCarlayl

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 
0

基於從裏克的反饋,下面是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服務器

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] 
+0

MySQL中沒有[]括號。 –

+0

@RickJames,謝謝你的信息。通過標籤,我不確定OP是否正在尋找適用於MySQL和SQL Server的解決方案,或者其中之一。我只是編輯了我的答案,以指定我的答案是針對SQL Server的。 – Tim