开发者

left join return null even if there are no rows

My tab开发者_运维百科les:

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?


You either need to turn your left join into a right join or swap the tables around:

SELECT cat.id, cat.name
  FROM user LEFT JOIN cat ON cat.id = user.catid
 WHERE user.id = 2

With your example data, this will give you a row containing nulls as a result.


Change your LEFT JOIN to a RIGHT JOIN... that should pull everything from the users table, and anything from the category table if it is available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜