SQL Select only rows where exact multiple relationships exist

后端 未结 10 1273
温柔的废话
温柔的废话 2020-12-06 02:06

This is closely related to this question, but adds another requirement.

Given a parent table \'parent\'

╔════════════╦════════╗
║ PARENT_ID  ║ NAME           


        
10条回答
  •  遥遥无期
    2020-12-06 02:38

    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.

提交回复
热议问题