运行复杂的查询

时间:2013-08-26 21:04:32

标签: java mysql sql database relational-database

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

userIDRoomID传递给查询。我不确定如何“循环”每个songID。我是否运行两个查询 - 首先获取每个songID,然后运行for循环以获取上述信息(使用Java)?

enter image description here

3 个答案:

答案 0 :(得分:2)

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

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

这是第二个问题

SELECT songID
FROM votes
WHERE UserID = @userid
      AND RoomID = @roomid

答案 1 :(得分: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

如果这不起作用,请尝试这一点 - 如果用户没有为该歌曲投票,则第三列将为null;如果是,则为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

答案 2 :(得分:1)

如果return为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