[英]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.