【问题标题】:Postgresql: Query returning incorrect dataPostgresql:查询返回不正确的数据
【发布时间】:2017-05-08 11:19:15
【问题描述】:

假设我有一个表empgroupinfo,并且我想获取恰好这两个 groupId 500 and 501(将动态出现)的员工 ID,不应该进入更多或更少数量的组,其中 empid != 102在 500 groupid 中。

我尝试了以下查询:

select empid from empgroupinfo 
where empgroupid in(500,501) and empid != 102
group by empid having count(empid) = 2

但上述查询也返回其他组中的 empId。

我想获取 empid 的情况,因为员工恰好在这两个 groupid(500 和 501)中,并且 empid != 102

【问题讨论】:

    标签: sql postgresql relational-division


    【解决方案1】:

    您的WHERE 子句选择empgroupid 为500 或501 的行,而不是empids,其中所有empgroupids 构成数组[500, 501]

    您可以在HAVING 子句中使用ARRAY_AGG

    SELECT empid 
    FROM empgroupinfo 
    GROUP BY empid
    -- ORDER BY clause here is important, as array equality checks elements position by position, not just 'same elements as'
    HAVING ARRAY_AGG(DISTINCT empgroupid ORDER BY empgroupid) = ARRAY[500, 501]
    

    根据[500, 501] 数组的来源,您可能不知道它本身是否已排序。在这种情况下,“包含 AND 被包含在”(运算符 @><@)也应该可以工作。


    #= CREATE TABLE empgroupinfo (empid int, empgroupid int);
    CREATE TABLE
    Time: 10,765 ms
    
    #= INSERT INTO empgroupinfo VALUES (1, 500), (1, 501), (2, 500), (2, 501), (2, 502);
    INSERT 0 5
    Time: 1,451 ms
    
    #= SELECT empid 
       FROM empgroupinfo 
       GROUP BY empid
       HAVING ARRAY_AGG(empgroupid ORDER BY empgroupid) = ARRAY[500, 501];
    ┌───────┐
    │ empid │
    ├───────┤
    │     1 │
    └───────┘
    (1 row)
    
    Time: 0,468 ms
    

    【讨论】:

    • @BunkerBoy:恐怕我不明白你的编辑。如果您不想要empId = 102,只需在查询中添加WHERE empId <> 102
    • 对不起,我犯了一个错误,这与 empid 无关!= 102 谢谢,现在我更正了谢谢,它对我有用..
    • 告诉我一件事假设如果我的 groupids 是 400 和 345 那么我必须根据查询按 asc 顺序排列我的数组吗?
    • 如果您知道数组是按降序排序的,那么您可以在ARRAY_AGG 中使用ORDER BY empgroupid DESC。但是如果顺序不同,在查询 Postgresql 之前对 id 进行排序可能会更容易。
    • @Marth 是否需要有连续的 group id 编号?对于这个 ARRAY_AGG(empgroupid ORDER BY empgroupid)
    【解决方案2】:

    试试:

    select empid 
    from empgroupinfo 
    group by empid 
    where empid <> 102
    having count(*) = 2 and min(empgroupid) = 500 and max(empgroupid) = 501
    

    【讨论】:

    • empgroupid 是动态的
    • empgroupid 只有两个可能的值?它们总是连续的吗?你能举出更多的例子吗?
    • 它将是随机的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多