首页 > 解决方案 > 根据群组成员资格选择

问题描述

假设我有两张桌子to. 我想选择t其中的所有行t.feature = o.feature(前两行)。

此外,我还想选择之前选择的行中t.grouping=t.grouping的所有行。在这种情况下1 , t.grouping2 ergo rows('E', 1)和. 实现这一目标的最优雅的方法是什么?('F', 2)('G', 1)

CREATE TABLE t
(   feature      VARCHAR,
    grouping            BIGINT
);

INSERT INTO t (feature, grouping)
VALUES ('A', 1), 
        ('B', 2),
        ('C', 5), 
        ('D', 4),
        ('E', 1), 
        ('F', 2),
        ('G', 1);
        
        
CREATE TABLE o
(   feature VARCHAR
);

INSERT INTO o (feature)
VALUES ('A'),
       ('B');

标签: sqlpostgresql

解决方案


如果我理解正确,试试这个...

with cte as 
(select grouping from t inner join o on t.feature=o.feature)
select t.* 
from t 
inner join cte on t.grouping=cte.grouping

或者

select 
* 
from t 
where grouping in 
(select grouping from t inner join o on t.feature=o.feature )

演示


推荐阅读