合并三个表,三个表都有aId字段,例如aId=10,如果其中只有一表符合条件,其它表则留空
例如:
a表结构:
aId field1 field2
b表结构:
aId field3 field4
c表结构:
aId field5 field6
如果现有aId=10,但三个表中有可能只有一个表有aId=10的数据,条件是至少有一个表有这个数据,查询出来的结果要求这样:
aId field1 field2 field3 field4 field5 field6
10 a b 空 空 空 空
就是说没有的就留空或其它字符填充。
------解决方案--------------------输出每个aId的SQL:
-----------------------------------------------
select
d.aId,
isnull(a.field1, ' ') as field1,
isnull(a.field2, ' ') as field2,
isnull(b.field3, ' ') as field3,
isnull(b.field4, ' ') as field4,
isnull(c.field5, ' ') as field5,
isnull(c.field6, ' ') as field6
from
(select distinct aId from A表
union
select distinct aId from B表
union
select distinct aId from C表) d
left join
A表 a
on d.aId=a.aId
left join
B表 b
on d.aId=b.aId
left join
C表 c
on d.aId=c.aId
------解决方案--------------------select a.aid , a.field1,a.field2,isnull(b.field3,null) as field3,isnull(b.field4,null) as field4,isnull(c.field5,null) as field5,isnull(c.field6,null) as field6
from a
left join b on a.aid = b.aid
left join c on a.aid = c.aid
------解决方案--------------------我觉得lz是不是这个意思
----------------------
select a.aid id,field1,field2,field3,field4,field5,field6
from a inner join b on a.aid = b.aid inner join c on a.aid = c.aid
union
select a.aid id,field1,field2,field3,field4,field5,field6
from a out join b on a.aid = b.aid out join c on a.aid = c.aid
order by id
------解决方案--------------------select
a.aId,a.field1,a.field2,b.field3,b.field4,c.field5,c.field6
from A表 a
left OUTER join B表 b on a.aId=b.aId
left OUTER join C表 c on a.aId=c.aId
------解决方案--------------------create table A(aID int, field1 varchar(10), field2 varchar(10))
go
create table B(aID int, field3 varchar(10), field4 varchar(10))
go
create table C(aID int, field5 varchar(10), field6 varchar(10))
go
insert B select 10, 'a ', 'b '
select * from A
full join B on A.aID=B.aID
full join C on A.aID=C.aID
--result
aID field1 field2 aID field3 field4 aID field5 field6
----------- ---------- ---------- ----------- ---------- ---------- ----------- ---------- ----------
NULL NULL NULL 10 a b NULL NULL NULL
(1 row(s) affected)