我没有太多的SQL经验,而且当涉及到比简单的INSERT / SELECT语句更先进的东西时,我几乎失去了。
我的情况是这样,我有以下两个表:
游戏 { int id,int finished }
提交 { int game_id,int user_id }
我想查询来自Games的任何id,其中finish = 0,并且特定的user_id在提交表中没有记住id。
换句话说,我希望找到一个未完成且特定用户没有玩过的游戏。
我知道我可以使用多个查询和逻辑(在java和jdbc中,如果它很重要),但我宁愿学习如何使用纯SQL做到这一点!
谢谢!
答案 0 :(得分:3)
SELECT g.id
FROM Games g
WHERE finished = 0
AND NOT EXISTS(SELECT *
FROM Submissions s
WHERE s.user_id = @userid
AND s.game_id = g.id)
或(如果您的RDBMS支持它)
SELECT id
FROM Games
WHERE finished = 0
EXCEPT
SELECT game_id
FROM Submissions
WHERE user_id = @userid
答案 1 :(得分:2)
SELECT g.id
FROM Games g
LEFT JOIN Submissions s ON g.id = s.game_id
AND s.user_id = 1234
WHERE g.finished = 0 AND s.user_id IS NULL
答案 2 :(得分:2)
select g.id from games g
where finished =0 and g.id not in
(select game_id from submissions s where s.player_id=@playerid)
答案 3 :(得分:0)
SELECT G.ID FROM Games G LEFT JOIN Submissions S ON
(G.ID = S.Game_ID AND S.User_ID = @UserID)
WHERE G.Finished = 0 AND S.User_ID IS NULL
编辑但现在与其他人相似。