Postgresql:查询返回不正确的数据
Postgresql: Query returning incorrect data
假设我有一个 table empgroupinfo
并且我想获取与这两个 groupId 500 and 501
完全相同的 employeeid 500 and 501
(将动态出现),不应该更多或更少的组数,其中 empid != 102
是在 500 groupid.
我试过以下查询:
select empid from empgroupinfo
where empgroupid in(500,501) and empid != 102
group by empid having count(empid) = 2
但是上面的查询还 returns 其他组中的 empId。
我想获取 empid
的情况,因为员工恰好在这两个组 ID(500 和 501)中并且 empid != 102
。
尝试:
select empid
from empgroupinfo
group by empid
where empid <> 102
having count(*) = 2 and min(empgroupid) = 500 and max(empgroupid) = 501
您的 WHERE
子句选择 empgroupid
为 500 或 501 的行,而不是 empid
,其中所有 empgroupid
组成数组 [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]
数组的来源,你可能不知道它本身是否排序。在那种情况下,"contains AND is contained by"(运算符 @>
和 <@
)也应该可以工作。
#= 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
假设我有一个 table empgroupinfo
并且我想获取与这两个 groupId 500 and 501
完全相同的 employeeid 500 and 501
(将动态出现),不应该更多或更少的组数,其中 empid != 102
是在 500 groupid.
我试过以下查询:
select empid from empgroupinfo
where empgroupid in(500,501) and empid != 102
group by empid having count(empid) = 2
但是上面的查询还 returns 其他组中的 empId。
我想获取 empid
的情况,因为员工恰好在这两个组 ID(500 和 501)中并且 empid != 102
。
尝试:
select empid
from empgroupinfo
group by empid
where empid <> 102
having count(*) = 2 and min(empgroupid) = 500 and max(empgroupid) = 501
您的 WHERE
子句选择 empgroupid
为 500 或 501 的行,而不是 empid
,其中所有 empgroupid
组成数组 [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]
数组的来源,你可能不知道它本身是否排序。在那种情况下,"contains AND is contained by"(运算符 @>
和 <@
)也应该可以工作。
#= 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