读书人

left join 怎么使用

发布时间: 2013-08-09 15:16:24 作者: rapoo

left join 如何使用?


select * from schedulingShipSchedule where Sub_ShipDate1<>''and Sub_Qty1<>'' and TeamHandlingBy='Non-Mailing'

以上代可以得到55


  with a as 
(select * from schedulingShipSchedule where Sub_ShipDate1<>''and Sub_Qty1<>'' and TeamHandlingBy='Non-Mailing'),
b as
(select * from DirectOrderV2soitems where invoiceornot='2' or invoiceornot='3')
select a.JobNumber,a.Version,b.HonourJob,b.itemnumber
from a left join b on
a.Version=b.itemnumber and a.JobNumber=b.HonourJob


什使用左接之後出63,什不是55?

[解决办法]
举例说明什么是一对多..

with a as
( select 1 'id', 'a1' 'x' union all
select 2 'id', 'a2' 'x' union all
select 3 'id', 'a3' 'x'
),
b as
( select 1 'id', 'b1' 'y' union all
select 2 'id', 'b21' 'y' union all
select 2 'id', 'b22' 'y' union all
select 2 'id', 'b23' 'y' union all
select 3 'id', 'b3' 'y'
)
select *
from a
left join b on a.id=b.id


-- 结果, a表数据3条,左连接之后出现5条记录.因为a.id=2的记录对应b.id=2有3条记录.
/*
id x id y
----------- ---- ----------- ----
1 a1 1 b1
2 a2 2 b21
2 a2 2 b22


2 a2 2 b23
3 a3 3 b3

(5 row(s) affected)
*/

读书人网 >SQL Server

热点推荐