sql—如果一列中的值存在于另一列中,则筛选行

wa7juj8i  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(560)

我在postgres 11中有下表:

col1   col2            col3               col4   
1      trial_1         ag-270              ag
2      trial_2         ag                  ag
3      trial_3         methotexate (mtx)   mtx
4      trial_4         mtx                 mtx
5      trial_5         hep-nor-b           nor-b

我想在col3列中搜索col4的每个值。如果col4中的值存在于col3中,我希望保留这些行,否则应该排除该行。
期望输出为:

col1   col2            col3               col4   
1      trial_1         ag-270              ag
2      trial_2         ag                  ag
3      trial_3         methotexate (mtx)   mtx
4      trial_4         mtx                 mtx

我不能在这方面做任何尝试,因为我还不能找到解决这个问题的办法。

rqenqsqc

rqenqsqc1#

如果 col4 存在于 col3 ,我想保留这些行。
... 转换为:

SELECT *
FROM   tbl a
WHERE  EXISTS (SELECT FROM tbl b WHERE b.col3 = a.col4);

db<>在这里摆弄
产生你想要的结果。

ca1c2owp

ca1c2owp2#

这可以作为内部联接来完成:

select distinct t.col1, t.col2, t.col3, t,col4
from T t inner join T t2 on t2.col3 = t.col4
yvt65v4c

yvt65v4c3#

select a.*
from myTable a
where exists (
    select 1
    from myTable b
    where b.col3 = a.col4)

如果您的表有许多行,您应该确保 col3 已编制索引。

相关问题