使用group by获取结果

时间:2014-10-17 01:17:55

标签: c# mysql group-by

我的数据库中有两个表:

song   => id, name, song_ref, views 
artist => id, name

我想从歌曲表中获取所有艺术家,每首歌曲中观看次数最多的歌曲。
我尝试使用MAX(views)来获取最大视图值,但没有成功获取此相关歌曲的其他字段。

SELECT a.name, MAX(s.views) FROM song s inner join artist a 
ON s.artist_ref = a.idArtist GROUP BY a.name

任何想法?谢谢

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT *
FROM
  (SELECT a.id AS aid,
          a.name AS artist,
          s.id AS sid,
          s.name AS most_viewed,
          s.views
   FROM artist a
   INNER JOIN song s ON s.artist_ref=a.id
   ORDER BY a.id,
            s.views DESC) c
GROUP BY c.aid;

答案 1 :(得分:1)

我的第一个回答是不正确的。这是一个有效的修订版本:

SELECT a.idArtist AS aid, a.name, s.id AS sid, s.views
FROM artist a INNER JOIN song s ON a.idArtist = s.artist_ref
INNER JOIN (SELECT MAX(views) AS views, artist_ref FROM song GROUP BY artist_ref) max_songs
ON s.artist_ref = max_songs.artist_ref AND s.views = max_songs.views
ORDER BY a.name

答案 2 :(得分:0)

试试这个..

SELECT a.name, 
(SELECT s.views FROM song s WHERE s.name=a.name 
ORDER BY s.views DESC LIMIT 0,1) as `views` 
FROM artist a

答案 3 :(得分:0)

这个小提琴是否返回正确的值(编辑的小提琴链接名称并包括返回具有最多查看歌曲的行的关联列的工作SQL语句)。

Link to Fiddle

它演示了以下带有测试数据的SQL语句。

SELECT a.Name, a.songRef, Views, aName  FROM artist b 
INNER JOIN song a on a.Name = b.aName 
   WHERE Views = 
      (SELECT MAX(Views) from Song as z
         WHERE z.Name = b.aName) GROUP BY a.name, b.aName, a.songRef