问题
I am trying to join two tables:
songs
id | song | artist
---|------|-------
1 | foo | bar
2 | fuu | bor
3 | fyy | bir
score
id | score
---|------
1 | 2
2 | 4
3 | 8
2 | 6
3 | 2
using this SQL command:
SELECT songs.id, songs.song, songs.artist, score.score FROM songs LEFT JOIN score ON score.id=songs.id ORDER BY songs.id, score DESC
What I get back is duplicates of the same song with multiple scores, I would like the score to be averaged.
result
id | song | artist | score
---|------|--------|-------
1 | foo | bar | 2
2 | fuu | bor | 4
2 | fuu | bor | 6
3 | fyy | bir | 8
3 | fyy | bir | 2
I tried that using:
SELECT songs.id, songs.song, songs.artist, ROUND(AVG(score.score),1) AS 'score' FROM songs INNER JOIN score ON score.id=songs.id ORDER BY score DESC
But that averages all scores, not just the score of each individual song
result
id | song | artist | score
---|------|--------|-------
1 | foo | bar | 4.4
回答1:
You need to GROUP BY all the fields you want to retain:
SELECT songs.id, songs.song, songs.artist,
AVG(score.score * 1.0) AS AvgScore
FROM songs
LEFT JOIN score
ON score.id=songs.id
GROUP BY songs.id, songs.song, songs.artist
ORDER BY songs.id, score DESC
Alternatively, you could just do this:
SELECT songs.id, songs.song, songs.artist,
(SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore)
FROM songs
回答2:
use "group by" songs.id
SELECT songs.id, songs.song, songs.artist,
ROUND(AVG(score.score),1) AS 'score' FROM songs
INNER JOIN score ON score.id=songs.id
group by songs.id ORDER BY score DESC
回答3:
Use this Select a.id,a.song,a.artist,avg(b.score) as score from songs a inner join score b on a.id =b.id Group by a.id,a.artist,a.song
回答4:
You need to GROUP BY
and join data to left (JOIN LEFT
)
try this:
SELECT
songs.id,
songs.song,
songs.artist,
ROUND(AVG(score.score), 1) AS 'score'
FROM songs
LEFT JOIN score ON score.id = songs.id
GROUP BY songs.id
ORDER BY score DESC
来源:https://stackoverflow.com/questions/38229899/sql-join-two-tables-with-avg