mysql join一个表为空_MySQL Left Join不为连接表返回空值

bd96500e110b49cbb3cd949968f18be7.png

Please help me with the following MySQL query, which joins two tables (A and B):

SELECT * from A

left join B on A.sid = B.sid

where (rCode = 1 Or rCode = 2 Or rCode = 3 Or rCode = 5)

AND (rYear = 2011 or rYear is null)

roleCode is a field in table A and rYear is a field in table B

The result set is not as expected. Only 185 rows are returned, but there are 629 rows in table A that match the where condition. Shouldn't the rows without a matching row in table B be returned with null values for their B fields?

解决方案

You should not specify rYear in a WHERE clause. Those limit your results after the join. You should specify rYear in an ON clause to get back records with NULL from table B.

SELECT * from A

left join B

on A.sid = B.sid

AND (rYear = 2011 or rYear is null)

where (rCode = 1 Or rCode = 2 Or rCode = 3 Or rCode = 5)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值