我知道如何检查两个表中是否存在值,但是如何添加列表明它找到了什么
SELECT NAME, ID FROM TABLE_A TA
WHERE EXISTS (SELECT 1 FROM TABLE_B TB
WHERE TA.ID = TB.ID)
结果
NAME ID
1 123
2 234
3 345
我想要什么
NAME ID Exists
1 123 Y
2 234 N
3 345 N
答案 0 :(得分:2)
可能是这个作品
SELECT NAME, ID,case when
(select count(1) from TABLE_B where ID = TA.ID) = 0 then 'N'
else 'Y'
end as 'Exists' FROM TABLE_A TA
WHERE EXISTS (SELECT 1 FROM TABLE_B TB
WHERE TA.ID = TB.ID)
答案 1 :(得分:2)
您可以在案例陈述中使用存在标准:
SELECT NAME, ID, CASE WHEN EXISTS (SELECT 1 FROM TABLE_B TB
WHERE TA.ID = TB.ID) THEN 'Y' else 'N' end [Exists] FROM TABLE_A TA
答案 2 :(得分:1)
SELECT TA.NAME, TA.ID,CASE WHEN TB.ID IS NULL THEN 'N' ELSE 'Y' END AS Y_N
FROM
(select NAME, ID FROM TABLE_A)TA LEFT JOIN
(SELECT ID FROM TABLE_B)TB ON
TA.ID = TB.ID
答案 3 :(得分:0)
SELECT NAME, COALESCE(TA.ID, TB.ID),
CASE WHEN TB.Id IS NULL OR TA.ID IS NULL THEN 'N' else 'Y' end [Exists]
FROM TABLE_A TA
FULL OUTER JOIN TABLE_B TB
ON TA.ID = TB.ID
这将为您提供两个表的结果,因此如果B中存在ID但不存在A,您也将获得resutls。
如果您只需要Tablea中值或不在B
中的值的结果SELECT NAME, TA.ID, CASE WHEN TB.Id IS NULL THEN 'N' else 'Y' end [Exists]
FROM TABLE_A TA
LEFT OUTER JOIN TABLE_B TB
ON TA.ID = TB.ID