MYSQL查询一对多关系

时间:2016-07-15 05:36:03

标签: mysql sql one-to-many

我有两张桌子: -

1- 部分

id    name   location_id
1     demo1     20
2     demo2     34

2- 设施

id    amenity_id   amenity_type object_id object_type

1   wedding_hall    venue_type     1          section

2  conference_hall  venue_type     1          section

3  conference_hall  venue_type     2          section

我想要所有那些其location_id为134并且拥有wedding_hall和conference hall的部分。我试过这个问题: -

    SELECT s.* from section s 
    INNER JOIN amenities am 
  on (am.object_type='section' AND am.object_id=s.id) 
WHERE s.location_id=134 AND 
(am.amenity_type LIKE 'venue_type' and am.amenity_id='wedding_hall') 
AND (am.amenity_type LIKE 'venue_type' and am.amenity_id='conference_hall')

如果我执行此查询: -

     SELECT s.* from section s 
 INNER JOIN amenities am 
on (am.object_type='section' AND am.object_id=s.id)
 WHERE s.location_id=134 AND 
(am.amenity_type LIKE 'venue_type' and am.amenity_id='wedding_hall')

然后它的工作原理不是一个以上的便利设施。 这是sqlfiddle

如何更正我的查询?

2 个答案:

答案 0 :(得分:2)

我认为你需要子查询。也许看一下EXISTS条件。如果该部分同时具有婚礼大厅和会议厅(但如果您只有两个婚礼大厅,并且它与多个区域合作),以下内容将为您提供所需的结果:

SELECT DISTINCT s.* FROM section s
    INNER JOIN amenities a
    ON a.object_id = s.location_id
        WHERE s.location_id = 134
    AND EXISTS(SELECT * FROM amenities WHERE object_id = s.location_id AND amenity_id = 'wedding_hall')
    AND EXISTS(SELECT * FROM amenities WHERE object_id = s.location_id AND amenity_id = 'conference_hall');

可能会在WHERE子句中添加amenity_type和object_type条件。

答案 1 :(得分:1)

如果我没有弄错你的问题并且你真的想要id = 1的部分,试试这个:

SELECT s.*
FROM section s
INNER JOIN amenities am
ON am.object_type='section' AND am.object_id=s.id
WHERE s.location_id=134
AND am.amenity_type LIKE 'venue_type'
AND am.amenity_id IN ('wedding_hall', 'conference_hall')
-- HAVING COUNT(DISTINCT am.amenity_id) > 1
GROUP BY s.id
HAVING COUNT(DISTINCT am.amenity_id) = 2

SQLFiddle Demo