繁体   English   中英

PostgreSQL:查询返回不正确的数据

[英]Postgresql: Query returning incorrect data

假设我有一个表empgroupinfo并且我想获取empgroupinfo这两个groupId 500 and 501 (将动态产生)的employeeid,不应将其加入或多或少的组号,其中empid != 102在500中groupid。

我试过以下查询:

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

但是,以上查询还返回其他组中的empId。

对于员工仅在这两个groupid(分别为500和501)中并且empid != 102的情况,我想获取empid

您的WHERE子句选择empgroupid为500或501的行, empgroupid选择所有empgroupid组成数组[500, 501] empgroupid ]的empid

您可以在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

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM