【问题标题】:How to perform Many to Many Relationship Filter Query如何执行多对多关系过滤查询
【发布时间】:2021-04-13 23:08:06
【问题描述】:

我想在 MySQL 中基于过滤器执行查询。首先,将在查询中使用的两个表如下:

设备:

Field Type
Id PK, Integer
Name Varchar(50)

食谱:

Field Type
Id PK, Integer
Name Varchar(50)

两个表之间的关系是多对多的,所以有一个数据透视表。

过滤器如下,你有一个recipe id数组,例如:

recipeIds = [1,2,3]

当前数据:

设备:

Id Name
100 A
101 B
102 C
103 D
104 E
105 F

食谱:

Id Name
1 Recipe 1
2 Recipe 2
3 Recipe 3
4 Recipe 4
7 Recipe 7
8 Recipe 8
9 Recipe 9

数据透视表:

EquipmentId RecipeId
100 1
100 4
101 1
101 2
103 9
103 7
104 1
104 2
104 3
105 1
105 2
105 3
105 8

然后查询应该将存在(或拥有)的设备返回到recipeIds中提到的配方:

查询结果(设备):

Id Name
104 E
105 F

其他设备应该不会出现,原因如下:

Equipment Reason
A Only recipe 1 is present, but not all 3 recipes mentioned
B Only recipe 1 and 2 is present, but not all 3 recipes mentioned
C Does not have any recipe
D Does not have any of the mentioned recipes

我不知道如何执行查询。我希望你的帮助。

【问题讨论】:

  • 我很困惑...您如何为两个表发布几行数据示例,并且可能暂时跳过JSON。专注于如何在纯 MySQL 中获得结果,然后只转换为您想要的 JSON 输出。顺便说一句,只需尝试编写查询并在那里实现您的条件。它不一定是一个有效的查询。一个你可以说明你所追求的就足够了。
  • 好的@FaNo_FN,我正在编辑帖子
  • 所以Pivot 是数据库中的真实表,对吗?不是查询生成的表?
  • 是的,是真正的桌子
  • 如果是这样,看来您只需要Pivot 进行recipes 检查和JOIN 它与Equipment 表一起获得Name

标签: mysql sql many-to-many


【解决方案1】:

试试这个查询:

SELECT P.EquipmentID, E.Name
FROM Pivot P 
JOIN Equipments E ON P.EquipmentID=E.Id
WHERE E.RecipeId IN (1,2,3) 
GROUP BY P.EquipmentID, E.Name
HAVING COUNT(*)=3;
  1. 加入PivotEquipments 表。
  2. 添加条件WHERE E.RecipeId IN (1,2,3)
  3. 添加GROUP BY P.EquipmentID, E.Name
  4. P.EquipmentID, E.Name中出现3次的任意组添加HAVING COUNT(*)=3;;有效匹配您的“仅出现在 Receipe 1,2,3 中的 EquipmentID”的条件

Here's a fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-14
    • 2020-08-02
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2013-08-28
    相关资源
    最近更新 更多