表1
Id
001
002
003
表2
id
001
004
我想显示table1的所有行,并像这样匹配table2的行
输出表
ID status
001 1 - Found
002 - 0
003 -0
1 - 发现 0 - 未发现
如何在SQL查询中实现
答案 0 :(得分:2)
select table1.id, case when table2.id is not null
then 'found'
end as status
from table1
left join table2 on table1.id = table2.id
答案 1 :(得分:2)
如果第二个表格可能有重复项,那么exists
和case
可能会更好:
select t1.*,
(case when exists (select 1 from table2 t2 where t1.id = t2.id)
then 'Found'
else 'Not Found'
end)
from table1 t1;
答案 2 :(得分:0)
像
这样的东西SELECT t1.*,
CASE
WHEN t2.ID IS NOT NULL
THEN 'FOUND'
ELSE 'NOT FOUND'
END [Status]
FROM Table1 t1 LEFT JOIN
Table2 t2 ON t1.ID = t2.ID
答案 3 :(得分:0)
使用LEFT JOIN
:
SELECT T1.Id, CASE WHEN T2.id IS NULL THEN 0 ELSE 1 END AS Status
FROM Table1 T1 LEFT JOIN
Table2 T2 ON T1.Id=T2.Id
结果:
ID STATUS
1 1
2 0
3 0
结果为SQL Fiddle。
如果您想显示Found
和Not Found
:
SELECT T1.Id, CASE WHEN T2.id IS NULL THEN 'Not Found' ELSE 'Found' END AS Status
FROM Table1 T1 LEFT JOIN
Table2 T2 ON T1.Id=T2.Id
结果:
ID STATUS
1 Found
2 Not Found
3 Not Found
小提琴示例here。
答案 4 :(得分:0)
你可以在以下情况下使用案例:
SELECT
Table1.id,
CASE WHEN
Table2.id IS NOT NULL THEN 1 ELSE 0
END
FROM
Table1
LEFT JOIN Table2 ON Table1.id = Table2.id