【问题标题】:Query multiple rows and columns on a single table in postgres在 postgres 中查询单个表上的多行和多列
【发布时间】:2016-09-15 14:52:20
【问题描述】:

我有下表

|------------------------------------| |所有者 |动物 |颜色 | |------------------------------------| |约翰 |狗 |黑色 | |彼得 |狗 |棕色 | |约翰 |猫 |绿色 | |丽莎 |狗 |白色 | |彼得 |猫 |黑色 | |------------------------------------|

我需要返回哪个主人有一只黑狗和一只绿猫,结果必须是“约翰”

我试过了,没有运气

从宠物中选择主人 在哪里 ( 存在(SELECT * FROM pets WHERE animal = 'dog' AND color = 'black') 和 存在(SELECT * FROM pets WHERE animal = 'cat' AND color = 'green') )

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    选择所有至少拥有其中一只宠物的人:

    select owner
    from pets
    where (animal, color) in ( ('dog', 'black'), ('cat', 'green'))
    

    这也将返回只有一只黑狗或一只绿猫的所有者,因此我们需要过滤掉那些确实有两只动物的人,这可以使用group byhaving 子句来完成

    select owner
    from pets
    where (animal, color) in ( ('dog', 'black'), ('cat', 'green'))
    group by owner
    having count(*) = 2;
    

    SQLFiddle 示例:http://sqlfiddle.com/#!15/4df52/1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 2016-12-08
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多