如何编写一个 sql 查询,以便对于每个搜索到的 id 都返回是否找到 id ? IN 语句中搜索的每个 id 都应该有一行,指定是否在表中找到具有该 id 的记录。
查询猜测
Select [id] From table1 Where [id] IN (1, 2, 3, 4, 5)
目标结果集
ID Found
1 yea
2 naw
3 yea
4 yea
5 naw
最佳答案
此版本不使用 IN
运算符,而是使用 union
来获取表表达式:
create table main(id int);
insert into main
select 1 union
select 3 union
select 5
select t.id,
case when count(m.id) > 0 then 'yep' else 'nope' end as found
from
(select 1 as id union
select 2 as id union
select 3 as id union
select 4 as id union
select 5 as id
)t
left join main m on t.id = m.id
group by t.id
输出:
id found
1 yep
2 nope
3 yep
4 nope
5 yep
关于mysql - SQL 返回搜索集和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487392/