即使没有行,左连接也返回 null
我的表:
表 cat
有 id, name
表 user
有 id, uname, catid
示例数据:
cat 表
1 | Cate one 2 | cate two
用户表
1 | sam | 1 2 | dam | 0
我的查询是
SELECT cat.id, cat.name
FROM cat LEFT JOIN user
ON cat.id = user.catid
WHERE user.id = 2
因为没有 id
0 的类别,所以我得到零行。
如果没有行,我想要 NULL
或零作为结果。
我该怎么做?
My tables:
Table cat
has id, name
Table user
has id, uname, catid
Sample data:
cat table
1 | Cate one 2 | cate two
user table
1 | sam | 1 2 | dam | 0
my query is
SELECT cat.id, cat.name
FROM cat LEFT JOIN user
ON cat.id = user.catid
WHERE user.id = 2
Since there is no category with id
0 I get zero rows.
If there are no rows I want NULL
or zeros as a result.
How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将左联接转换为右联接,或者交换表:
对于示例数据,这将为您提供包含空值的行。
You either need to turn your left join into a right join or swap the tables around:
With your example data, this will give you a row containing nulls as a result.
将您的
LEFT JOIN
更改为RIGHT JOIN
...这应该从用户表中提取所有内容,并从类别表中提取任何内容(如果可用)。Change your
LEFT JOIN
to aRIGHT JOIN
... that should pull everything from the users table, and anything from the category table if it is available.