This is closely related to this question, but adds another requirement.
Given a parent table \'parent\'
╔════════════╦════════╗
║ PARENT_ID ║ NAME
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 can do this with a group by.
SELECT PARENT_ID FROM link_tbl WHERE PROP_ID IN (5,1) GROUP BY PARENT_ID HAVING COUNT(*) = 2
If you want to select all parents with at least a 5 and a 1, you can use:
SELECT PARENT_ID
FROM rel
GROUP BY PARENT_ID
HAVING 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
With two nested subqueries, like this..
Select pa.Id
From parents pa
Where not exists -- This ensures that all specifies properties exist
(Select * From property y
Where propertyId In (1,5)
And Not Exists
(Select * From parentProperty
Where parentId = pa.parentId
And propertyId = y.propertyId ))
And not exists -- This ensures that only specified list of properties exist
(Select * From parentProperty
Where parentId = pa.parentId
And propertyId Not In (1,5) )
The first one reads "Show me all the parents where there is not a property in the specified list of properties that is not in the parent properties table for the specified parent...."
The second subquery reads: "also make sure that there does not exist a record in the parentProperties table for that parent for any property that is not in the specified list."
If MySql supported minus
, the query could look like this:
select parent_id
from rel
where prop_id in (5,1)
group by parent_id
having count(distinct prop_id)=2 and count(prop_id)=2
minus
select parent_id
from rel
where prop_id not in (5,1);
The not in
will remove those relationships that exceed (5,1), e.g. (5,1,3).
I know you're using MySql and my answer hence is wrong. Just take it as another idea.
SELECT PARENT_ID
FROM rel
GROUP BY PARENT_ID
HAVING SUM(PROP_ID NOT IN (5,1)) = 0
AND SUM(PROP_ID = 1) = 1
AND SUM(PROP_ID = 5) = 1