Postgresql: Query returning incorrect data

元气小坏坏 提交于 2019-12-02 08:15:32

Your WHERE clause selects rows where empgroupid is either 500 or 501, not empids where all the empgroupids form the array [500, 501].

You could use an ARRAY_AGG in the HAVING clause:

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]

Depending on where the [500, 501] array comes from, you may not know whether it itself is sorted or not. In that case a "contains AND is contained by" (operators @> and <@) should work too.


#= 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

Try:

select empid 
from empgroupinfo 
group by empid 
where empid <> 102
having count(*) = 2 and min(empgroupid) = 500 and max(empgroupid) = 501
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!