Skip to main content
1 of 5
Erwin Brandstetter
  • 182.1k
  • 28
  • 457
  • 620

The key word here is "relational division".

For the given specifications, it won't get faster than this::

SELECT package_id
FROM   package_to_message p1
JOIN   package_to_message p2 USING (package_id)
JOIN   package_to_message p3 USING (package_id)
WHERE  p1.message_id = (SELECT m.id FROM messages m WHERE m.name = 'message_name_1')
AND    p2.message_id = (SELECT m.id FROM messages m WHERE m.name = 'message_name_2')
AND    p3.message_id = (SELECT m.id FROM messages m WHERE m.name = 'message_name_3')
AND    NOT EXISTS (  -- no other!
   SELECT FROM package_to_message p0
   WHERE  p0.package_id = p1.package_id
   AND    p0.message_id NOT IN (p1.message_id, p2.message_id, p3.message_id)
   );

But maybe you need a more generic query ...

See:

Erwin Brandstetter
  • 182.1k
  • 28
  • 457
  • 620