简体   繁体   English

子查询中的MySQL交集

[英]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. 我正在尝试通过apartsments_features表创建一个列表(公寓)的过滤器,其中包含与apartment features的多对多关系。

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. 我意识到太晚了,我无法在MySQL中使用INTERSECTMINUS

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. 我很确定有一种方法可以做到这一点,但目前我的知识仅限于简单的左右连接。

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. 将此查询的结果加入到apartments表中以获取名称等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM