left join 的On 与查询条件 where 的疑难杂症

newmankind 2005-10-12 05:40:59

1、
select a.col1 ,count(*) as qty
from a
left join b on b.col2 = a.col2 and b.role = 3 and b.void = 'n'
left join c on a.col1 = c.col1
where c.void= 'n'
group by a.col
2、
select a.col1 ,count(*) as qty
from a
left join c on a.Col2 = c.Col2 , b
where c.void= 'n' and a.Col1 = b.Col1 and b.role = 3 and b.void = 'n'
group by a.col1

对于2 语句能完全符合要求,为什么1不能呢,是left join 的On 的问题。why?高手指教!
...全文
467 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
MorningTea 2005-10-14
  • 打赏
  • 举报
回复
:.(
谁说,我是一个侧面布赖特.彼特,呵呵
zxbyhcsdn 2005-10-14
  • 打赏
  • 举报
回复

你还犯了一个错误!
她是茶MM 不是茶兄!

哈哈!!!
MorningTea 2005-10-14
  • 打赏
  • 举报
回复
你写的东西误导我,你可以给出表,几笔数据,然后列出结果集,否则你只说语句,我只知道有没有错误而已!
newmankind 2005-10-12
  • 打赏
  • 举报
回复
上面的错误代码,也错了 :)
这是我最常犯的低级错误,不知道大家有没有类似的。
select a.col1 ,count(b.col2) as qty ,max(c.otherinf)
from a
left join b on b.col2 = a.col2
left join c on a.col1 = c.col1
where c.void= 'n' and b.role = 3 and b.void = 'n'
group by col1
newmankind 2005-10-12
  • 打赏
  • 举报
回复
另,我试过Inner join
a数据
col1 col2
---------
c1 b1
c1 b2
c2 b2
b中对应数据
role col2 void
------------------
3 b1 n
3 b2 Y
3 b2 n


select a.col1,a.col2,b.role
from a inner join b on a.col2 = b.col2 and b.void = 'n'




select a.col1,a.col2,b.role
from a inner join b on a.col2 = b.col2
就不是一样的结果
newmankind 2005-10-12
  • 打赏
  • 举报
回复
茶兄,我之所以采取On后面限制单表方式是为了避免这样一种很容易犯的逻辑错误,

若a中存在下面的数据
col1 col2
---------
c1 b1
c1 b2
c2 b2
b中对应数据
role col2 void
------------------
3 b1 n
2 b2 n
c中数据
col1 void otherinf
--------------------
c1 n inf1
c2 n inf2

想得到的结果是
c1 1 inf1
c2 0 inf2

很容易把代码写成
select a.col1 ,count(b.col2) as qty ,c.otherinf
from a
left join b on b.col2 = a.col2
left join c on a.col1 = c.col1
where c.void= 'n' and b.role = 3 and b.void = 'n'
group by col1
后来被这样的错误搞怕了,才想找出真正的left join 解决之道



MorningTea 2005-10-12
  • 打赏
  • 举报
回复
你考虑问题方向偏了:

首先你不要管你到底第一句有没有达到你的要求
你要理解a left join b on 。。。的用法,就是a 集合 按照on后面的条件关联的交集并上a集合其他不符合条件的纪录,另外关联时候on后面加上的是2表关联的字段条件,而不是一些单表的条件
例如:left join b on b.col2 = a.col2 --2表关联
and b.role = 3 and b.void = 'n' --这些是率选条件,不要写在on里面

你画几个文氏图,自己看看,到底是要怎样的集合,选择left join ,right join 等等
不管怎样,标准形式类似:
a left join b on a.col1 = b.col12 ...
left join c on b.col3 = c.col4 ...
where a.col2 = 'xx' and b.col5 = 'xx' and c.col1 = 'xx' ...
newmankind 2005-10-12
  • 打赏
  • 举报
回复
to:happygong(高兴)
我现在要求的就是Left join 的限定条件,就是把b表里的符合 b.role = 3 and b.void = 'n'
的条件的数据全部选出来与 a关联,
我试过On条件出现字符串时,可以的

to:wgsasd311(自强不息)
能不能说的再详细点,我现在要的就是语句2的结果
wgsasd311 2005-10-12
  • 打赏
  • 举报
回复
第一条语句和第二条语句不是一个意思,第一条语句包括第二条语句。
happygong 2005-10-12
  • 打赏
  • 举报
回复
第二条语句严格限制b.void='h'
而第一条语句是放在LeftJoin的On里面,即使不满足,由于LeftJoin也可能被选出来
在On中只能出现字段名称,不应该出现数字与字符串

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧