mysql - 具有奇数一对多关系的高效 SQL 模式设计

标签 mysql database-schema

我试图找出一种有效且高效的方法来实现两个表之间的以下关系,Lists(ListID, ListName)Items(ItemID, ItemName, Cost, Description, QuantityNeeded, QuantityPurchased),在 MySQL 数据库中:

A list can have many items. However, the Description, QuantityNeeded, and QuantityPurchased attributes in the Items table are specific to a list. For example, say one item has the attributes 1, Paper Towels, 5.99, NULL, 4, 2, and another is 2, Paper Towels, 5.99, NULL, 7, 0. Even though these have the same ItemName and Cost, 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/

相关文章:

mysql - 按日期对 MYSQL 结果行进行分组

php - 从列表中获取匹配的 MySQL 行?

mysql - ORDER BY 第一个 OR 条件为 true

php - 比当前查询更好的方法来组合随机分类条目?

带有 "Open Schema"的数据库 - 好主意还是坏主意?

php - 如何更新一个sql db

oracle - 为什么我可以创建同义词但不能授予同一个表的选择权?

python - 如何在 Python 中通过 API 查询在 SQL Alchemy 中插入关系数据(多对多)

ruby-on-rails-3 - 数据库 :test:load with Rails 上的 SQLException

mysql - 使用关系数据库跟踪库存随时间和空间的变化