【问题标题】:Selecting all photos that contains specific people选择包含特定人物的所有照片
【发布时间】:2019-11-04 02:36:21
【问题描述】:

我有一个 SQL 表,有两列 [photo,person]。我浏览了每张照片,假设第一张照片包含 Ben 和 Harry,所以我插入了两行。

我的桌子现在看起来像这样。

Photo, Person

1, Ben

1, Harry

我希望能够选择同一张照片中包含 Ben 和 Harry 的所有照片(但不仅限于 Ben 和 Harry,如果照片中有其他人也可以)。我尝试搜索示例语句,但无法获得我想要的查询的措辞。我该怎么做?

【问题讨论】:

标签: mysql sql


【解决方案1】:

按照片分组并在HAVING子句中设置条件:

select photo
from tablename
group by photo
having sum(person in ('Ben', 'Harry')) = 2

或:

select photo
from tablename
where person in ('Ben', 'Harry') 
group by photo
having count(*) = 2

【讨论】:

    【解决方案2】:

    像这样?

     Select distinct photo from your_table where person in ("Ben", "Harry")
    

    where person in ("Ben", "Harry") - 获取人是 Ben 或 Harry 的所有行

    DISTINCT - 从结果中删除重复的照片

    更新:

    SELECT A.photo FROM your_table A WHERE A.person = "Ben" AND exists (SELECT 1 FROM your_table B where A.photo = B.photo AND A.person = "Harry")
    

    在这里,我选择了带有 Ben 的所有行,并使用子查询将结果也限制为带有 Harry 的行。

    【讨论】:

    • 抱歉,我编辑了我的问题。我想选择 Ben 和 Harry 在同一张照片中的照片。
    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多