zabbix=# EXPLAIN ANALYZE SELECT e.* FROM events e WHERE EXISTS (SELECT NULL FROM functions f, items i, hosts_groups hgg JOIN rights r ON r.id = hgg.groupid AND r.groupid IN ( '50', '56' ) WHERE e.objectid = f.triggerid AND f.itemid = i.itemid AND i.hostid = hgg.hostid GROUP BY f.triggerid HAVING Min(r.permission) > 0 AND Max(r.permission) >= 2) AND e.object = '0' AND e.source = '0' ORDER BY e.clock LIMIT 1 offset 0; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ----- Limit (cost=0.56..60.97 rows=1 width=40) (actual time=144448.271..144448.271 rows=0 loops=1) -> Index Scan using events_2 on events e (cost=0.56..76416746.08 rows=1265166 width=40) (actual time=144448.270..144448.270 rows=0 loops=1) Index Cond: ((source = 0) AND (object = 0)) Filter: (SubPlan 1) Rows Removed by Filter: 5327405 SubPlan 1 -> GroupAggregate (cost=1.40..29.60 rows=1 width=12) (actual time=0.026..0.026 rows=0 loops=5327405) Filter: ((min(r.permission) > 0) AND (max(r.permission) >= 2)) -> Nested Loop (cost=1.40..29.58 rows=1 width=12) (actual time=0.026..0.026 rows=0 loops=5327405) -> Nested Loop (cost=1.13..27.79 rows=5 width=16) (actual time=0.007..0.013 rows=5 loops=5327405) -> Nested Loop (cost=0.85..27.04 rows=2 width=16) (actual time=0.005..0.008 rows=1 loops=5327405) -> Index Scan using functions_1 on functions f (cost=0.42..10.13 rows=2 width=16) (actual time=0.002..0.002 rows=1 loops=5327405) Index Cond: (e.objectid = triggerid) -> Index Scan using items_pkey on items i (cost=0.42..8.45 rows=1 width=16) (actual time=0.002..0.003 rows=1 loops=7585157) Index Cond: (itemid = f.itemid) -> Index Only Scan using hosts_groups_1 on hosts_groups hgg (cost=0.28..0.34 rows=3 width=16) (actual time=0.001..0.002 rows=3 loops=7585 157) Index Cond: (hostid = i.hostid) Heap Fetches: 14175150 -> Index Scan using rights_2 on rights r (cost=0.28..0.35 rows=1 width=12) (actual time=0.002..0.002 rows=0 loops=24504337) Index Cond: (id = hgg.groupid) Filter: (groupid = ANY ('{50,56}'::bigint[])) Rows Removed by Filter: 4 Total runtime: 144448.351 ms (23 rows)