Zahymaka
Zahymaka

Reputation: 6641

MySQL intersection in subquery

I'm trying to create a filter for a list (of apartments), with a many-to-many relationship with apartment features through the apartsments_features table.

I would like to include only apartments that have all of some features (marked 'Yes' on a form) excluding all the ones that have any of another set features (marked 'No'). I realized too late that I couldn't use INTERSECT or MINUS in MySQL.

I have a query that looks something like:

SELECT `apartments`.* FROM `apartments` WHERE `apartments`.`id` IN (
    SELECT `apartments`.`id` FROM `apartments` INTERSECT (
        SELECT `apartment_id` FROM `apartments_features` WHERE `feature_id` = 103 
INTERSECT SELECT `apartment_id` FROM `apartments_features` WHERE `feature_id` = 106
    ) MINUS (
    SELECT `apartment_id` FROM `apartments_features` WHERE `feature_id` = 105 UNION 
    SELECT `apartment_id` FROM `apartments_features` WHERE `feature_id` = 107)
)
ORDER BY `apartments`.`name` ASC

I'm pretty sure there's a way to do this, but at the moment my knowledge is restricted to little more than simple left and right joins.

Upvotes: 1

Views: 1841

Answers (2)

user359040
user359040

Reputation:

A slightly different way of doing it:

select a.*
from apartments a
join apartments_features f1 
on a.apartment_id = f1.apartment_id and f1.feature_id in (103,106) -- applicable features
where not exists
(select null from apartments_features f2
 where a.apartment_id = f2.apartment_id and f2.feature_id in (105,107) ) -- excluded features
group by f1.apartment_id
having count(*) = 2 -- number of applicable features

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838876

You could try something like this:

SELECT apartment_id
FROM
(
    SELECT apartment_id
    FROM apartments_features
    WHERE feature_id IN (103, 106)
    GROUP BY apartment_id
    HAVING COUNT(*) = 2
) T1
LEFT JOIN
(
    SELECT apartment_id
    FROM apartments_features
    WHERE feature_id IN (105, 107)
) T2
ON T1.apartment_id = T2.apartment_id
WHERE T2.apartment_id IS NULL

Join the result of this query to the apartments table to get the name, etc.

Upvotes: 2

Related Questions