sql-查询赋值问题

asd100230520 2013-05-07 03:47:32
假如 表名 为 table 结构如下

id score
1 60
2 50

这时 select * from table where id = 3 是没有记录的
但是我想得到
id score
3 0
这样的结果
求 大神 帮帮忙啊(要一条语句搞定)
...全文
73 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
asd100230520 2013-05-07
  • 打赏
  • 举报
回复
引用 1 楼 ap0405140 的回复:

create table table1(id int, score int)

insert into table1
 select 1, 60 union all 
 select 2, 50


declare @id int
select @id=3

select @id 'id',
       isnull((select score 
               from table1
               where id=@id),0) 'score'

/*
id          score
----------- -----------
3           0

(1 row(s) affected)
*/


declare @id int
select @id=1

select @id 'id',
       isnull((select score 
               from table1
               where id=@id),0) 'score'

/*
id          score
----------- -----------
1           60

(1 row(s) affected)
*/
谢谢 搞定了
MrYangkang 2013-05-07
  • 打赏
  • 举报
回复
引用 3 楼 DBA_Huangzj 的回复:
先把你的业务背景说清楚,要抓住规则来写,不然你这次是3,下次id要4的话,就不通用了。我猜你这个应该是找出所有人的成绩,没有的就用0代表吧?应该还有一些表的,left join 加上isnull就可以了。
版主说的好
發糞塗牆 2013-05-07
  • 打赏
  • 举报
回复
先把你的业务背景说清楚,要抓住规则来写,不然你这次是3,下次id要4的话,就不通用了。我猜你这个应该是找出所有人的成绩,没有的就用0代表吧?应该还有一些表的,left join 加上isnull就可以了。
q465897859 2013-05-07
  • 打赏
  • 举报
回复
这不是三国杀 不能无中生有 可以关联系统表整一个出来
declare @tb table(id int,score int)
insert @tb
select 1,   60 
union 
select 2,   50

select a.number id,ISNULL(b.score,0 )score from (select * from master..spt_values where type='p' and number>0)a  left join @tb b on a.number=b.id
where  a.number=3
唐诗三百首 2013-05-07
  • 打赏
  • 举报
回复

create table table1(id int, score int)

insert into table1
 select 1, 60 union all 
 select 2, 50


declare @id int
select @id=3

select @id 'id',
       isnull((select score 
               from table1
               where id=@id),0) 'score'

/*
id          score
----------- -----------
3           0

(1 row(s) affected)
*/


declare @id int
select @id=1

select @id 'id',
       isnull((select score 
               from table1
               where id=@id),0) 'score'

/*
id          score
----------- -----------
1           60

(1 row(s) affected)
*/

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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