问题描述
您好,我是sql的初学者,但是我想知道如何解决以下问题。
下面是带有CA CB的列表,因此,如果CA CB中的值出现在CB中,则CA返回true,否则返回false。
CA CB
6 5
5 6
2 3
3 2
4 1
结果应该像这样
CA CB
6 5 True
5 6 True
2 3 True
3 2 True
4 1 False
如果有人知道如何编写sql来表达它? 非常感谢!
解决方法
您可以使用别名不同的同一个表的自联接来完成
select t1.ca,t1.cb,case when t2.ca is not null
then 'true'
else 'false'
end as result
from your_table t1
left join your_table t2 on t1.cb = t2.ca
,
我建议使用exists
:
select t.*,(exists (select 1
from t t2
where t2.ca = t.cb and t2.cb = t.ca
)
) as flag
from t;
这是我推荐此方法的一些原因。
首先,exists
对重复项不敏感。您不指定给定对是否可以出现多次。但是如果可以的话,left join
可以乘以行。
第二,不需要case
表达式。 MySQL支持布尔值,因此您只能使用布尔表达式。
第三,这两种方法之间的性能应该非常相似(假设没有重复;如果有重复,这可能会更快)。 exists
和left join
都可以在(ca,cb)
上使用索引。
编辑:
如果要过滤不匹配的对,则可以在not exists
子句中使用where
:
select t.*
from t
where not exists (select 1
from t t2
where t2.ca = t.cb and t2.cb = t.ca
);
,
仅出于贡献,您也可以这样做:
select *,case when CA in (select distinct CB from YOUR_TABLE) or
CB in (select distinct CA from YOUR_TABLE)
then 'False'
else 'True'
end as check_1
from YOUR_TABLE
我仅看到您关于如何显示True
行的问题,
with cts as
(
case when CA in (select distinct CB from YOUR_TABLE) or
CB in (select distinct CA from YOUR_TABLE)
then 'False'
else 'True'
end as check_1
from YOUR_TABLE
)
select * from cts where check_1 = 'True'