SQL 表规范化:有关限制记录参与多对多关系的简单问题
如果您有以下表格和关系:
- 产品表
- 价格点表(一种产品的一个或多个价格)
- 版本表(在同一区域销售的一组产品)
以及任何产品中只能存在一个产品价格的约束给定版本。 您将如何构建表格来反映限制?
为了说明限制,我有一个价格为 1 美元、2 美元和 3 美元的产品。 我有 A、B、C、D、E、F、G、H、I 的媒体区域(每个区域代表俄亥俄州哥伦布这样的地方)
product A price $1 goes to A, B, C
product A price $2 goes to D, E, F
product A price $3 goes to G, H, I
产品 A 存在于 A、B、C 时价格为 1 美元,不能有其他价格(2 美元) , $3) in A, B, C
将版本 M2M 表转换为 PricePoints,然后在 M2M 表上的所有字段减去 PricePoint 字段上放置唯一索引是否可行? (在打字时思考)是否有更好的方法来表示关系?
If you have the following tables and relations:
- A Product table
- A Price Point table (one or more prices for a product)
- A Version table (groups of products sold in the same area)
and the constraint that only one product price can exist in any given version. How would you construct the tables to reflect the constraints?
To illustrate the restriction, I have a product priced at $1, $2, and $3.
I have media zones of A, B, C, D, E, F, G, H, I (each representing a place like Columbus OH)
product A price $1 goes to A, B, C
product A price $2 goes to D, E, F
product A price $3 goes to G, H, I
Product A price $1 when it exists in A, B, C cannot have other prices ($2, $3) in A, B, C
Would a Version M2M table to PricePoints, then put a unique index on the M2M table on all fields minus the PricePoint field work? (thought about it while typing this out) Is there a better way to represent the relationships?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有点难以理解你的问题。我不明白“产品 A 价格为 1 美元,当它存在于 A、B、C 时不能存在于 D、E、F、G、H、I 中。”这句话。为了这个答案,我假设“版本”和“媒体区”是同一件事。
使用包含三个字段的中间定价表:product_id、version_id 和price_id。该表的主键(如果您选择使用增量非智能键,则为唯一索引)是(product_id,version_id)。
I'm having a little trouble understanding your question. I don't understand the statement "Product A price $1 when it exists in A, B, C cannot exist in D, E, F, G, H, I.". I'm going to assume, for the sake of this answer, that "version" and "media zone" are the same thing.
Use an intermediate Pricing table with three fields: product_id, version_id, and price_id. The primary key of this table (or a unique index if you choose to use an incremental non-intelligent key) is (product_id, version_id).
以下是我如何根据提供的数据构造表来反映约束:
SQL DDL:
SQL DML(成功=好):
SQL DML(失败=好):
Here's how I would construct the tables to reflect the constraints, based on the data supplied:
SQL DDL:
SQL DML (succeeds = good):
SQL DML (fails = good):
除非您可以明确地说仅在特定区域允许产品价格组合,否则我认为最好放弃数据约束并在存储过程或其他业务层使用业务规则约束来检查在尝试之前存在哪些数据将产品-价格-区域组合添加到数据库中。
Unless you can definitively say that a product-price combination is only allowed in specific regions, I think it's better to forgo a data constraint and use a business rule constraint at a stored procedure or other business layer to check to see what data exists before attempting to add product-price-region combinations to the database.