sql查询where提交in的问题

zhengbin215 2011-11-24 03:01:44
例如有一张表 a 字段有
id score
1 80
2 90
3 100

我要给予一个查询条件 select * from a where id in (1,2,3,4,5)

能否显示的结果为
1 80
2 90
3 100
4 0
5 0
表中不存在的也显示出来,分数默认为0
谢谢
要实现这种情况有哪些方法?程序或sql都行.
...全文
155 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhengbin215 2011-11-24
  • 打赏
  • 举报
回复
1,2,3,4,5..等编号数量是随机变化的,只是可以肯定的是唯一标识
pengxuan 2011-11-24
  • 打赏
  • 举报
回复

if object_id('tb','U') is not null
drop table tb
go
create table tb
(
id int,
score int
)
go
insert into tb
select 1,80 union all
select 2,90 union all
select 3,100
go
select number,isnull(score,0) from master..spt_values a left join tb b on a.number=b.id where type='p' and number between 1 and 5
go
/*
number
----------- -----------
1 80
2 90
3 100
4 0
5 0

(5 行受影响)
*/
--小F-- 2011-11-24
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 flysql 的回复:]
select b.id,isnull(a.score,0) as score
from
(select 1 as id union select 2 union select 3 union select 4 union select 5) b
left join a on a.id=b.id
[/Quote]
.
快溜 2011-11-24
  • 打赏
  • 举报
回复
select * from a right join (select 1 as id union select 2 
union select 3 union select 4 union select 5) b
on a.id =b.id
sql_sf 2011-11-24
  • 打赏
  • 举报
回复
IF NOT OBJECT_ID('tb') IS NULL 
DROP TABLE tb
Go
CREATE TABLE tb ( [id] INT, [score] INT )
INSERT tb
SELECT 1 ,
80
UNION ALL
SELECT 2 ,
90
UNION ALL
SELECT 3 ,
100
Go
SELECT a.number ,
ISNULL(b.[score], 0) [score]
FROM master.dbo.spt_values a
LEFT JOIN dbo.TB b ON a.number = b.ID
WHERE type = 'P'
AND number IN ( 1, 2, 3, 4, 5 )
/*
number score
----------- -----------
1 80
2 90
3 100
4 0
5 0

*/
-晴天 2011-11-24
  • 打赏
  • 举报
回复
create table tb(id int,score int)
insert into tb select 1,80
insert into tb select 2,90
insert into tb select 3,100
go
select a.number,isnull(b.score ,0)score
from master..spt_values a left join tb b on a.number=b.id
where type='p' and a.number in(1,2,3,4,5)
/*
number score
----------- -----------
1 80
2 90
3 100
4 0
5 0

(5 行受影响)

*/
go
drop table tb
FlySQL 2011-11-24
  • 打赏
  • 举报
回复
select b.id,isnull(a.score,0) as score
from
(select 1 as id union select 2 union select 3 union select 4 union select 5) b
left join a on a.id=b.id
AcHerat 元老 2011-11-24
  • 打赏
  • 举报
回复

;with cte as
(
select 1 as row
union
select 2
union
select 3
union
select 4
union
select 5
)

select a.row,isnull(b.score,0) score
from cte a left join tb b on a.row = b.id

34,838

社区成员

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

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