【问题标题】:Sqlite select column contains each of idsSqlite 选择列包含每个 id
【发布时间】:2020-02-20 20:05:51
【问题描述】:

我有一张桌子

 CREATE TABLE humans_to_pets (
        human_id   INT  NOT NULL,
        pet_id     INT  NOT NULL
    )

我在哪里存储人类拥有什么宠物的配对(多对多)。

给定 pet_id 列表,我需要从列表中找到拥有每只宠物的所有人类。

例如

human_id |  pet_id
1           11
2           11
2           12
3           13
4           11
4           12           

find([11,12]) 应该返回 [2, 4]。只有人类 2 和 4 拥有宠物 11 和 12。

我使用的是 sqlite 3.31

【问题讨论】:

    标签: sql sqlite group-by


    【解决方案1】:

    您可以使用聚合,并使用having 子句进行过滤:

    select human_id
    from humans_to_pets
    where pet_id in (11, 12)
    group by human_id
    having count(distinct pet_id) = 2
    

    假设(pet_id, human_id) 元组是唯一的(这对这个联结表来说是有意义的),这可以简化为不使用distinct,这样可以提高查询效率:

    select human_id
    from humans_to_pets
    where pet_id in (11, 12)
    group by human_id
    having count(*) = 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 2020-05-14
      • 2021-11-13
      • 2011-01-05
      • 2015-10-17
      相关资源
      最近更新 更多