一个看似简单的sql,告急!

电脑不需要休息吗? 2008-01-18 08:58:18
有如下两个表
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

请各位高手指点!
...全文
117 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
JL99000 2008-01-18
  • 打赏
  • 举报
回复
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
JL99000 2008-01-18
  • 打赏
  • 举报
回复
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

接分了
  • 打赏
  • 举报
回复
谢谢各位大哥指点!小弟谢了!
一者仁心 2008-01-18
  • 打赏
  • 举报
回复
select u.id,isnull(t.num,0) from user u left join temp t on u.id=t.id
shirley_yue 2008-01-18
  • 打赏
  • 举报
回复
答案楼上
nj_1st_excellence 2008-01-18
  • 打赏
  • 举报
回复
select user.name,ISNULL(temp.num,0) AS num from user
left join temp on user.ID=temp.USERID
wedding123 2008-01-18
  • 打赏
  • 举报
回复
select a.name,ISNULL(b.num,0) from user a LEFT OUTER JOIN
temp b on
a.id=b.userid

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧