在多种条件下选择MySQL中的多对多关系

时间:2014-05-07 21:15:31

标签: mysql sql many-to-many

让我们假设我们有一个小的MySQL数据库:

女性:

  • id_woman
  • 名称

women_shoes:

  • id_woman(FK)
  • id_shoe(FK)

鞋类:

  • id_shoe
  • 名称

woman_handbags:

  • id_woman(FK)
  • id_handbag(FK)

手提包:

  • id_handbag
  • 名称

多对多有两种关系。我想从这样的DB获得的是:选择所有有鞋的女性:耐克,美洲狮,芒果和手袋:versace。我对那些穿着各种鞋子和每个手提包的女性都很感兴趣。我知道东西的名字,我想知道这些名字。

2 个答案:

答案 0 :(得分:1)

也许是这样的?如果我理解你的问题。

SELECT 
    r.* 
FROM recipe r
JOIN recipe_ingredients ri ON ri.id_recipe = r.id_recipe
JOIN ingredients i ON i.id_ingredient = ri.id_ingredient
JOIN recipes_tags rt ON rt.id_recipe = r.id_recipe
JOIN tags t ON t.id_tag = rt.id_tag
WHERE i.name = 'ziemniaki' 
   OR i.name = 'cebula'
  AND t.tag = "tani" 
   OR t.tag = "łatwy"
GROUP BY r.id_recipe
HAVING COUNT(r.id_recipe) > 3 -- all 4 of the criteria have been met
;

请参阅工作FIDDLE以获得澄清

基本上这样做是在满足四个标准之一时返回一行。除此之外,它还将仅返回具有至少一种成分和至少一种标签的配方。因此,当返回4行(或更多行)时,符合所请求参数的配方的条件

答案 1 :(得分:1)

由于第二个标准只有1个手提包,因此您不需要从子查询中进行选择,但我认为它可能会改为多个手提包。

SELECT
    w.*
FROM women w 
JOIN 
(
    SELECT
        id_woman
    FROM woman_shoes ws 
    JOIN shoes s ON ws.id_shoe = s.id_shoe
    WHERE s.name IN ('puma','nike','mango')
    GROUP BY id_woman
    HAVING COUNT(*) = 3
) has_shoes hs ON hs.id_woman = w.id_woman
JOIN 
(
    SELECT
        id_woman
    FROM woman_handbags wh 
    JOIN handbags h ON wh.id_handbag = h.id_handbag
    WHERE h.name IN ('versace')
    GROUP BY id_woman
    HAVING COUNT(*) = 1
) has_handbag hb ON hb.id_woman = w.id_woman