2012年4月25日 星期三

Sql语句写法及left join, right join注意事项

轉自:本文地址:http://enjoyasp.net/?p=557


用 join后, 条件要写在之后
select * from bdCustomerAllocate a
left join bdFollowRecord b
on ( a.id = b.allocateid and b.id = (select top 1 id  from bdFollowRecord where allocateid = a.id order by followdate desc ))
where a.SalesStaff = 'liuhong'
而不要用:
select * from bdCustomerAllocate a
left join bdFollowRecord b
on a.id = b.allocateid
where a.SalesStaff = 'liuhong'
and b.id = (select top 1 id  from bdFollowRecord where allocateid = a.id order by followdate desc )
保证where 句中的条件都是from 后的表,而不是join的表

1,条件写在left join, right join集合内。
(作left join得到的join 集合一般是统计数据,故与统计相关的条件都要放在left join之内)

(1)  SELECT DISTINCT c.account FROM frmUser c
(2)  LEFT JOIN bdCustomerAllocate a
(3)  ON c.Account = a.SalesStaff
(4)  WHERE a.SalesStaff in ( SELECT ControlAccount FROM permUserRelation WHERE CurrentAccount = 'luni' )

若执行前三步,则结果是以frmUser为主的数据集,若全部执行,得到的结果好象以bdCustomerAllocate为主,没有达到左连接的效果。原因:分清where的作用,前三步得到的数据集,在where中会将不满足条件的除去,因是以左连接bdCustomerAllocater的SalesStaff作判断,故结果集将以bdCustomerAllocater为主,没有达到左连接效果。

故在写 left join 时,join 的数据集最好执行去掉全部条件,而不是在left join之后再用where去除。
SELECT DISTINCT c.account FROM frmUser c
LEFT JOIN ( SELECT SalesStaff FROM bdCustomerAllocate WHERE SalesStaff in ( SELECT ControlAccount FROM permUserRelation WHERE CurrentAccount = 'luni' ) ) a
ON c.Account = a.SalesStaff

2,子集合后要有另名:
SELECT * FROM ( SELECT * FROM bdCustomerAllocate ) a  //无别名a是错误的,因为不指定别名,怎么在条件中引用数据集中的字段。

3, from 后的 join是对表集合的一种补充

SELECT DISTINCT c.account,d.* FROM frmUser c
JOIN bdCustomerAllocate a
ON c.Account = a.SalesStaff
, bdCustomerAllocate d

join相当于对from后的表对一种补充,之后再用逗号引用其它表。下面的是错误的,因为join作用在紧跟它的表后面,此时会作用在d上,d没有account
SELECT DISTINCT c.account,d.* FROM frmUser c, bdCustomerAllocate d
JOIN bdCustomerAllocate a
ON c.Account = a.SalesStaff

沒有留言: