获取未在已连接表中记录的行

时间:2015-07-09 08:41:42

标签: mysql

tables

如上图所示,我得到了这3张表。

我的目标是让所有bits user 1(jm)没有做出反应。

目前我有这个MySQL代码:

select * from bit b LEFT JOIN bit_reaction br ON (br.bitId=b.id AND br.userId != 1)

这里的问题是返回bit_reaction。id = 2,因为br.userId不等于1.正确的行为是它只返回id为2和3的位。

感谢您的提示!

2 个答案:

答案 0 :(得分:1)

select b.*
from bit b
left join bit_reaction br ON br.bitId = b.id 
                         AND br.userId = 1
WHERE br.bitId is null

答案 1 :(得分:0)

我认为你希望每个用户都能做出反应。所以更通用的答案是...

SELECT *
FROM bit AS tBit
LEFT JOIN user AS tUser ON 1 = 1
LEFT JOIN bit_reaction AS tReaction ON tBit.id = tReaction.bitID
    AND tUser.id = tReaction.userID
WHERE tReaction.userID IS NULL