关于 select in()返回结果问题

tj_libo 2020-08-13 01:37:09
请教一下 如果将in中的结果都显示出来,不存在则返回0.
比如:
select * from table1 where id in(1,2,3,4)
实际上数据库只有2条数据,为id=1,id=2的
如何将结果显示成
id value
1 value1
2 value2
3 0
4 0

...全文
270 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

SELECT ISNULL(a.id,b.number),ISNULL(a.value,0) FROM table1 a RIGHT JOIN(

SELECT number FROM master.dbo.spt_values WHERE [type]='P' AND number in(1,2,3,4)) b
ON a.id=b.number
这个id数据字表你可以自己构建,自带的这个只支持到2047
tj_libo 2020-08-13
  • 打赏
  • 举报
回复
引用 1 楼 唐诗三百首 的回复:

select id=a.id,
       value=isnull(b.value,0)
 from (select id=1 union all
       select id=2 union all
	   select id=3 union all
	   select id=4) a
 left join (select * 
            from table1 
			where id in(1,2,3,4)) b on a.id=b.id
试过了 不行 加了时间 group后 还是只有1条数据 其他的不显示
唐诗三百首 2020-08-13
  • 打赏
  • 举报
回复

select id=a.id,
       value=isnull(b.value,0)
 from (select id=1 union all
       select id=2 union all
	   select id=3 union all
	   select id=4) a
 left join (select * 
            from table1 
			where id in(1,2,3,4)) b on a.id=b.id

34,576

社区成员

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

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