【问题标题】:Filter rows if value in one column exists in another column如果一列中的值存在于另一列中,则过滤行
【发布时间】:2020-10-23 12:16:24
【问题描述】:

我在 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

我无法对此进行任何尝试,因为我还无法找到解决方案。

【问题讨论】:

  • 为什么最后一行(带有col1 = 5的那一行)被排除在外? 'nor-b''hep-nor-b' 的子字符串。
  • nor-b 在 'col3' 中不作为一个完整的字符串存在(作为一个子字符串存在)
  • 是的,'nor-b' (col4) 是 'hep-nor-b' (col3) 的最后 (5) 个字符。
  • 或者你的意思是(完全)平等?但是只有col1 = 2col1 = 4 的行才会出现在结果中。
  • 是的,我的意思是完全平等

标签: sql postgresql filter exists


【解决方案1】:
select a.*
from myTable a
where exists (
    select 1
    from myTable b
    where b.col3 = a.col4)

如果你的表有很多行,你应该确保col3被索引。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果col4 中的值存在于col3 中,我想保留这些行。

      ...翻译成:

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

      db小提琴here

      产生你想要的结果。

      【讨论】:

        猜你喜欢
        • 2019-12-03
        • 2020-07-19
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多