MySQL左连接显示缺少行的NULL

时间:2018-11-15 07:53:37

标签: mysql

我有2张桌子

表格:

recip
recipid | recipname
  1     |   Recip1
  2     |   Recip2

和表格:

recipuser
recipid | userid
  1     |  1
  2     |  1
  1     |  2

所以用户ID 2有1条密码

我想要实现的结果是显示给定用户ID EG的所有匹配或为null的“食谱”行:

SELECT r.recipid, r.recipname, ru.userid
FROM recip r
left JOIN recipuser ru ON r.recipid = ru.recipid
WHERE ru.userid = 2 OR ru.userid IS NULL 

结果:

recipid | recipname | userid
  1     |   Recip1  |   2

我想得到:

recipid | recipname | userid
  1     |   Recip1  |   2
  2     |   Recip2  |   NULL

对于给定用户ID的每一行,我如何显示带有用户ID或NULL的recip中的所有行?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

WHERE逻辑移至ON子句:

SELECT r.recipid, r.recipname, ru.userid
FROM recip r
LEFT JOIN recipuser ru
    ON r.recipid = ru.recipid AND ru.userid = 2;

当前查询的问题是WHERE子句正在过滤掉要显示的不匹配记录。