查找具有值A的行和值为B的行的所有ID

时间:2017-11-30 19:16:20

标签: sql postgresql select

我有一张这样的表:

+-----+-------+-----+
| id  | value | ... |
+-----+-------+-----+
| 1   | A     | ... |
| 1   | B     | ... |
| 1   | C     | ... |
| 2   | B     | ... |
| 2   | C     | ... |
| 3   | A     | ... |
| 3   | C     | ... |
| 4   | B     | ... |
| 4   | A     | ... |
| ... | ...   | ... |
+-----+-------+-----+

我想将此限制为id只有value列中包含A行和B行的行+-----+-------+-----+ | id | value | ... | +-----+-------+-----+ | 1 | A | ... | | 1 | B | ... | | 1 | C | ... | | 4 | B | ... | | 4 | A | ... | | ... | ... | ... | +-----+-------+-----+ 。在这种情况下,表格如下所示:

id

...因为value 2和3都没有let getLinkTopicsSql = "SELECT Topic.Id, Topic.Name, isnull( (select 1 from FeaturedTopic where TopicId = Topic.Id),0) as IsFeatured FROM Topic INNER JOIN LinkTopic ON LinkTopic.TopicId = Topic.Id INNER JOIN Link ON LinkTopic.LinkId = Link.Id WHERE Link.Id = @LinkId" 列中的A和B.

是否有简洁的方法来查找这些ID?

2 个答案:

答案 0 :(得分:2)

select id, value
from t
where id in (
    select id
    from t
    group by id
    having bool_or(value = 'A') and bool_or(value = 'B')
)

select id, value
from t t0
where 
    exists (
        select 1
        from t
        where id = t0.id and value = 'A'
    ) and
    exists (
        select 1
        from t
        where id = t0.id and value = 'B'
    ) 

答案 1 :(得分:1)

这样做的一种方法是计算id的a / b的不同数量:

SELECT *
FROM   mytable
WHERE  id IN (SELECT   id
              FROM     mytable
              WHERE    value in ('a', 'b')
              GROUP BY id
              HAVING   COUNT(DISTINCT value) = 2)