您的位置:首页 > 其它

关于left join 查询的一个小误区

2012-07-21 18:30 155 查看
两个表 a b

a

ID 代码 颜色 类别

1 yy 红色 1

2 dd 白色 2

b

ID 代码 名称 类别

1 dd 社保科 1

2 dd 劳务科 2

3 xx 保卫科 1

4 xx 资料室 2

5 yy 宣传科 2

sql:

select a.代码,a.颜色,b.名称 from a left join b on a.代码=b.代码 where a.类别=1 and b.类别=1

结果

代码 颜色 名称

---------------------- 无记录 ,显然这不是我想要的

原来 在left join 查询中,where语法如果 加了限制右表 b的条件 ,就会参与到整个查询中

修改

select a.代码,a.颜色,b.名称 from a left join b on a.代码=b.代码 and a.类别=b.类别 where a.类别=1

结果正确

select a.代码,a.颜色,b.名称 from a left join b on a.代码=b.代码 and b.类别=1 where a.类别=1 语法错误

顺便说一句 ,如果有多个表lieft join,在access中,需要用括号

select a.代码,a.颜色,b.名称,c.x from ((a left join b on a.代码=b.代码 and a.类别=b.类别) left join c on a.id=c.id ) where a.类别=1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: