繁体   English   中英

仅从两个表查询中选择最高结果

[英]Selecting only top result from two table query

这是我的两个表:
歌曲:

+--------+---------------------+
| SongID |    SongDeviceID     |
+--------+---------------------+
|   3278 | 1079287588763212246 |
|   3279 | 1079287588763212221 |
|   3280 | 1079287588763212230 |
+--------+---------------------+

投票:

+--------+--------+
| SongID | UserID |
+--------+--------+
|   3278 |     71 |
|   3278 |     72 |
|   3279 |     71 |
+--------+--------+

我试图计算votes表中的条目votes (对于每个唯一的SongID并返回SongDeviceID的条目的SongDeviceID

这是我到目前为止:

SELECT Songs.SongDeviceID, COUNT(*) FROM Votes INNER JOIN Songs ON Votes.SongID = Songs.SongId GROUP BY Votes.SongID, Songs.SongDeviceID ORDER BY count(*) DESC

哪个回报:

+---------------------+----------+
|    SongDeviceID     | Count(*) |
+---------------------+----------+
| 1079287588763212246 |        2 |
| 1079287588763212221 |        1 |
+---------------------+----------+

更新:查询已更新,以处理获取SongDeviceID但我仍然需要帮助只返回第一行。

首先

SELECT  SongID,COUNT(*) from votes GROUP BY SongID order by count(*) DESC LIMIT 1

然后你想要歌曲设备名称

SELECT SongID,COUNT(*),SongDeviceID
from
  votes 
left join 
   Songs on votes.songid = song.songid
GROUP BY
   SongID 
order by 
   count(*) DESC LIMIT 1

尝试这个

   SELECT Songs.SongDeviceID, COUNT(*) FROM Votes INNER JOIN Songs ON Votes.
    SongID =  Songs.SongId GROUP BY Votes.SongID, Songs.SongDeviceID ORDER BY count(*) 
    DESC LIMIT 1
select top 1
    S.SongDeviceID, COUNT(distinct V.UserID) as 'UserVotes'
from
   Songs as S
join 
  Votes as V on V.SongID = S.SongID
group by
   S.SongDeviceID
order by
  UserVotes DESC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM