我有以下表格:
platforms(id,platformname)
games(id,title,platformid)
gameslists(id,memberid,gameid)
我想从游戏表中选择所有记录,但不包括games.gameid存在于特定成员的游戏列表中的记录。所以用简单的英语:从游戏表中选择所有记录,除了游戏列表中存在游戏列表的那些记录,其中memberid等于999(memberid将来自会话)。我还需要平台名称,但我认为这是一个简单的内部联接。
我尝试了这个,以及其他变化,但无济于事!
SELECT DISTINCT games.id, platforms.platformname, gameslists.gameid
FROM games
INNER JOIN platforms ON games.platformid = platforms.id
INNER JOIN gameslists ON games.id = gameslists.gameid
WHERE platformid = 1 and gameslists.memberid <> 999
ORDER BY games.releasedate DESC
LIMIT 8
答案 0 :(得分:1)
SELECT g.*
FROM GAMES g
LEFT JOIN GAMESLISTS gl ON gl.gameid = g.id
AND gl.memberid = ?
WHERE gl.id IS NULL
SELECT g.*
FROM GAMES g
WHERE g.id NOT IN (SELECT gl.gameid
FROM GAMESLISTS gl
WHERE gl.memberid = ?)
SELECT g.*
FROM GAMES g
WHERE NOT EXISTS(SELECT NULL
FROM GAMESLISTS gl
WHERE gl.gameid = g.id
AND gl.memberid = ?)
在MySQL中,LEFT JOIN/IS NULL is the most efficient means of getting a list based on what to exclude, but only if the columns being compared are not nullable(连接条件中的值不能为空)。 Otherwise, the NOT IN and NOT EXISTS are more efficient
由于外键,比较的列不太可能为NULL,因此请使用LEFT JOIN / IS NULL。但请注意,您不需要专门用于排除数据的JOIN。
答案 1 :(得分:1)
从Stack Overflow自己的Jeff Atwood中查看this guide