2016-07-06 84 views
0

两个表我试图连接两个表:SQL JOIN与AVG

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 

使用此SQL命令:

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 

我得到的回复是有多个得分同一首歌的副本,我希望得分是平均的。

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 

我试过用:

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 

但是,平均所有得分,而不仅仅是得分每一个人首歌曲的

result 
id | song | artist | score 
---|------|--------|------- 
1 | foo | bar | 4.4 
+1

添加'集团By' .. –

+0

成绩没有主键,这可能证明是有问题。 – Strawberry

回答

3

您需要GROUP BY所有字段要保留:

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 

或者,你可能只是这样做:

SELECT songs.id, songs.song, songs.artist, 
    (SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore) 
FROM songs 
0

使用 “组由” 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 
+0

不需要在每个答案中都说出来。 OP问问题获得答案,所以他肯定会尝试。没有刺耳的感情;) –

+0

@Prdp:我删除它。但在大多数情况下,我们没有得到任何答复,至少它的工作或没有:( –

0

使用此 选择a.id,a.song,一.artist,avg(b.score)作为歌曲评分a内部加入评分b对a.id = b.id 分组a.id,a.artist,a.song

0

您需要GROUP BY并加入数据向左(JOIN LEFT

试试这个:

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