SQL Select only rows where exact multiple relationships exist SQL Select only rows where exact multiple relationships exist sql sql

SQL Select only rows where exact multiple relationships exist


SELECT PARENT_IDFROM relGROUP BY PARENT_IDHAVING SUM(PROP_ID NOT IN (5,1)) = 0   AND SUM(PROP_ID = 1) = 1    AND SUM(PROP_ID = 5) = 1


This alternative has the benefit of a constant statement structure and only one parameter, independent of the amount of relations you are looking for:

SELECT parent_id FROM rel GROUP BY parent_id HAVING GROUP_CONCAT(prop_id ORDER BY prop_id ASC SEPARATOR ",") = '1,5';

Disadvantages:

  • You need to prepare an ordered, comma separated String of prop_ids upfront.
  • This works on MySQL, but not all database servers.


If you want to select all parents with at least a 5 and a 1, you can use:

SELECT PARENT_IDFROM relGROUP BY PARENT_IDHAVING SUM(PROP_ID = 1)       AND SUM(PROP_ID = 5)       AND SUM(PROP_ID NOT IN (5,1)) = 0

If you need exactly one 5 and one 1, see this answer