user表的ID字段与temp表的userID形成外键关系
我想写一条sql查询语句获得结果如下
name num
a 5
b 0
c 6
d 0
e 0
即name与num对应,没有对应num值得纪录为0
请各位高手指点!
...全文
1177打赏收藏
一个看似简单的sql,告急!
有如下两个表 user ID name 1 a 2 b 3 c 4 d 5 e temp ID userID num 1 1 5 2 3 6 user表的ID字段与temp表的userID形成外键关系 我想写一条sql查询语句获得结果如下 name num a 5 b 0 c 6 d 0 e 0 即name与num对应,没有对应num值得纪录为0 请各位高手指点!
if object_id('[user]') is not null
drop table [user]
if object_id('temp') is not null
drop table temp
go
create table [user](ID int,name varchar(10))
insert into [user]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e'
create table temp(ID int,userID int,num int)
insert into temp
select 1,1,5 union all
select 2,3,6
select a.name,isnull(b.num,0) as num from [user] a left join temp b on a.ID=b.userID
if object_id('[user]') is not null
drop table [user]
if object_id('temp') is not null
drop table temp
go
create table [user](ID int,name varchar(10))
insert into [user]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e'
create table temp(ID int,userID int,num int)
insert into temp
select 1,1,5 union all
select 2,3,6
select a.name,isnull(b.num,cast(0 as varchar(5))) as num from [user] a left join temp b on a.ID=b.userID