比较 SQL 中的两个表,并在新列中将等于行设置为"True"



有人能解释SQL在TableResult中查询以下结果吗。

TableA                        TableB                    TableResult
Id | Function                 Id | Function              Id | Function | Compare
---|----------               ----|----------            ----|----------|---------
1  | code1                    1  | code1                 1  | code1    | true
2  | code2                    2  | code4                 2  | code2    | false
3  | code3                    3  | code5                 3  | code3    | false
4  | code4                                               4  | code4    | true

有两个表TableATableB,两个表中的Function列都是唯一的。TableA中的整个数据应该在ResultTable中,如果TableB函数在TableA函数中等于,则ResultTable Compare列必须为true,否则为false。

有人能建议如何在SQL中获得所需的结果吗。

如有任何帮助,将不胜感激

您可以使用EXISTS:

select a.*,
exists (select 1 from TableB b where b.function = a.function) compare
from TableA a  

或:

select a.*,
case 
when exists (select 1 from TableB b where b.function = a.function) then 'true'
else 'false'
end compare
from TableA a 

请参阅演示

使用LEFT JOIN并测试是否匹配。

SELECT a.*, IF(b.id IS NULL, 'false', 'true') AS compare
FROM tableA AS a
LEFT JOIN tableB AS b ON a.function = b.function

最新更新