我试图找出一种有效且高效的方法来实现两个表之间的以下关系,Lists(ListID, ListName)
和 Items(ItemID, ItemName, Cost, Description, QuantityNeeded, QuantityPurchased)
,在 MySQL 数据库中:
A list can have many items. However, the
Description
,QuantityNeeded
, andQuantityPurchased
attributes in theItems
table are specific to a list. For example, say one item has the attributes1, Paper Towels, 5.99, NULL, 4, 2
, and another is2, Paper Towels, 5.99, NULL, 7, 0
. Even though these have the sameItemName
andCost
, they are from different lists.
实现它的最佳方式是什么?我考虑过将 ListID
属性添加到 Items
表中,以便每个项目“知道”它是哪个列表的一部分,但这可能会导致非常冗长的 WHERE
执行(正确?),我希望它尽可能高效。
最佳答案
应用程序关系不在表之间,它们在值(或如此标识的实体)之间并由表表示。
添加
-- list ListID has member ItemId
-- UNIQUE/PK (itemID)
-- FK (listID) references Lists
-- FK (itemID) references Items
Member(ListID, itemID)
或将 Items 替换为
-- list ListID has member ItemId and item ItemId ...
-- UNIQUE/PK (ItemID)
-- FK (ListID) referencing Lists
ItemsX(ListID, ItemID, ItemName, Cost, Description, QuantityNeeded, QuantityPurchased)
前者很难在SQL 中约束也具有FK Items (ItemID) 引用Member 的等价物,即每个项目都必须是某个列表的成员。因此通常会使用后者。
注意
ItemsX = ListID, i.* from Member m join Items i on m.ItemID = i.ItemId
Items = select ItemID,... from ItemsX
Member = select ListID, ItemID from ItemsX
如果您不知道直接模型的选项,那么您就没有足够的知识来担心“效率”。您需要更多的设计(包括约束)和查询经验。您的情况几乎在任何通过订单和订单(行)项目而不是列表和项目的信息建模介绍中得到解决。
关于mysql - 具有奇数一对多关系的高效 SQL 模式设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896314/