SQL返回搜索集和结果

时间:2015-05-27 15:52:01

标签: mysql

如何搜索sql查询,以便在搜索到的每个id时返回是否找到id?在IN语句中搜索的每个id都应该有一行,指定是否在表中找到了具有该id的记录。

查询猜测

<%= link_to 'New Guide', new_category_guide_path(@category) %>

目标结果集

Select [id] From table1 Where [id] IN (1, 2, 3, 4, 5)

2 个答案:

答案 0 :(得分:1)

此版本不使用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

答案 1 :(得分:0)

这是一种使用临时表而不是IN运算符或多个联合的方法。

创建临时表

Declare Global Temporary Table session.temp (id decimal(15, 0))

填充临时表

Insert Into session.temp (id) values ((1),(2),(3),(4),(5))

查询

SELECT session.temp.id,
       case when count(table1.id) > 0 Then 'Yep' Else 'Nope' End As Found
FROM session.temp
LEFT JOIN table1
ON session.temp.id = table1.id
GROUP BY temp.id