简体   繁体   中英

Selecting only top result from two table query

Here are my two tables:
Songs:

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

Votes:

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

I am trying to count the number of entries in the votes table (for each unique SongID and return the SongDeviceID of the entry with the most.

This is what I have so far:

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

Which returns:

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

UPDATE: The query has been updated to take care of getting the SongDeviceID but I still need help returning only the first row.

for first

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

and you want song device name then

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

Try this

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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