现在有两张表,内容分别为,其中cid为tabledetails表的主键,在tablemain中可为空tablemain
id cid
1 1
2 1
3 2
4 null
5 nulltabledetails
cid name
1 中国
2 美国
3 日本现在求一句select语句,使得输出结果为:id cid name
1 1 中国
2 1 美国
3 2 日本
4 null null
5 null null求该SQL语句!
id cid
1 1
2 1
3 2
4 null
5 nulltabledetails
cid name
1 中国
2 美国
3 日本现在求一句select语句,使得输出结果为:id cid name
1 1 中国
2 1 美国
3 2 日本
4 null null
5 null null求该SQL语句!
b.name
from tablemain a left join tabledetails b
on a.cid=b.cid
from tablemain t left join
tabledetails r on t.id=r.cid
from tablemain a
left join tabledetails b
on a.id=b.cid
from tablemain t left join
tabledetails r on t.id=r.cid
---测试数据---
if object_id('[tablemain]') is not null drop table [tablemain]
go
create table [tablemain]([id] int,[cid] int)
insert [tablemain]
select 1,1 union all
select 2,1 union all
select 3,2 union all
select 4,null union all
select 5,null
if object_id('[tabledetails]') is not null drop table [tabledetails]
go
create table [tabledetails]([cid] int,[name] varchar(4))
insert [tabledetails]
select 1,'中国' union all
select 2,'美国' union all
select 3,'日本'
---查询---
select a.*,b.name
from tablemain a
left join tabledetails b
on a.id=b.cid
---结果---
id cid name
----------- ----------- ----
1 1 中国
2 1 美国
3 2 日本
4 NULL NULL
5 NULL NULL(所影响的行数为 5 行)
from tablemain a
left join tabledetails b
on a.id=b.cid数据有问题吧
select a.*,b.name from tablemain a left join tabledetails b on a.cid=b.id
from tablemain t left join
tabledetails r on t.id=r.cid
所以要用左连接查询:
select a.*,
b.name
from tablemain a left join tabledetails b
on a.cid=b.cid
from tablemain a left join tabledetails b on a.cid=b.cid
from tablemain a left join tabledetails b on a.cid=b.cid
SELECT A.*,B.name FROM tablemain A left join tabledetails B
A.cid = B.cid
from details B right join
main A on A.id=B.cid
result
//-*-------
1 1 中国
2 1 美国
3 2 日本
4 NULL NULL
5 NULL NULL
select a.id,a.cid,b.name from tablemain a left join tabledetails b on a.id=b.cid
b.name
from tablemain a left join tabledetails b
on a.cid=b.cid