0

我的目标是做两件事: - 计算特定房间中每个
人的数量votes(此表称为votes) 。 - 查明用户 ID 是否至少对一首歌曲投票(在特定房间)songID

和被传递到查询中userIDRoomID我不确定如何“循环”每个songID. 我是否运行两个查询 - 首先获取每个查询songID,然后运行一个for循环来获取上述信息(为此使用 Java)?

在此处输入图像描述

4

3 回答 3

2

您可以针对第一个问题执行此操作

SELECT Count(songID), songID
FROM votes
WHERE RoomID = @roomid
GROUP BY songID

这是第二个问题

SELECT songID
FROM votes
WHERE UserID = @userid
      AND RoomID = @roomid
于 2013-08-26T21:24:29.877 回答
1
select SongID, count(*) as voteCount, 
case when exists( 
        select 1 from votes b 
        where b.songID = a.songId and b.RoomID = ? and b.UserID = ? ) 
    then 'Yes' else 'No' end case as didUserVote
from votes a
where a.RoomID = ?
group by SongID

如果这不起作用,试试这个 - 如果用户没有投票给这首歌,第三列将为空,UserID如果他们这样做了。

select a.SongID, count(*) as voteCount, b.UserID
from votes a left join votes b on a.songID = b.songID and b.RoomID = ? and b.UserID = ?
where a.RoomID = ?
group by a.SongID, b.UserID
于 2013-08-26T21:18:35.110 回答
1

如果 retunr 为 NULL 则在第三列尝试此操作 没有投票

select SongID, count(*) as voteCount,(
        select b.userid from votes b 
        where b.songID = a.songId and b.RoomID = 131 and b.UserID = 70)
    from votes a
    where a.RoomID = 131
    group by SongID
于 2013-08-26T21:21:21.587 回答