22,210
社区成员
发帖
与我相关
我的任务
分享
create table A(a_id int,b_id int,c_id int)
insert into a values(1 ,1 ,1)
insert into a values(2 ,null ,1)
insert into a values(3 ,1 ,null)
insert into a values(4 ,null ,null)
create table B(b_id int,type1 varchar(10))
insert into b values(1 ,'BB')
create table C(c_id int,type2 varchar(10))
insert into c values( 1 ,'CC')
go
--方法一
select a.a_id,
type1 = (select b.type1 from b where b.b_id = a.b_id),
type2 = (select c.type2 from c where c.c_id = a.c_id)
from a
--方法二
select a.a_id,
b.type1,
c.type2
from a left join b on a.b_id = b.b_id
left join c on a.c_id = c.c_id
drop table a , b, c
/*
a_id type1 type2
----------- ---------- ----------
1 BB CC
2 NULL CC
3 BB NULL
4 NULL NULL
(所影响的行数为 4 行)
*/
select a.a_id,
(select b.type1 from b where b.b_id = a.b_id),
(select c.type1 from c where c.c_id = a.c_id)
from a