我正在从事需要多值 M : N 关系的项目。
例如。
Products
表中有一个产品列表。
用户可以购买 1 种或多种产品并保存在 Orders
表中。除了这些信息之外,还有一个表用于维护分析信息。
这个表应该包含像这样的硬编码数据。如果订单包含产品 1 和产品 2 那么产品 3 和产品 4 是否也出现在用户的订单中。这些基本上是硬编码规则
actual products | expected products
1,3 | 2,4
5,6,7,8 | 3,4
现在从这些表中,我需要找到信息,例如如果用户的订单号 1 有类似 1 和 3 的产品,然后返回 2 和 4。
我需要有关如何描述这种多值 M 到 N 关系的建议。如果有 RDBMS 以外的任何其他选项,请随时提出建议。谢谢
最佳答案
您可以创建另外三个表:
- ProductSet(productset_id) - 存储产品集标题(样本中的一行)
- ProductSetPart(productset_id,product_id) - 存储需要设置的产品,在您的情况下列为实际产品
- ProductSetAdditional(productset_id,product_id) - 存储预期的产品。
在给出订单后,我们可以检测应该添加哪些额外的产品。
编辑:添加示例
返回满足要求的集合列表的示例查询:
SELECT psp.productset_id FROM
ProductSetPart psp LEFT JOIN
OrderLines ol
ON
psp.product_id=ol.product_id
GROUP BY
psp.productset_id
HAVING
-- trick - COUNT(*) will return count of all products required by aggregatet set
-- COUNT(psp.product_id) will count only not null products
-- (which will be null if they aren't in order line)
-- so if all product sets are in order line then we know,
-- that this set requirements are full filled
COUNT(*) = COUNT(psp.product_id)
关于mysql - 多值M建模的方法有哪些 : N relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37393422/