SQL - 我是否可以将表主键基于多个字段,并要求第一个或第二个值的唯一性?
假设我们有一个产品目录。表有以下字段: 公司ID 和 产品ID 。我希望表主键基于这两个字段,因此当其 CompanyID 和 ProductID 字段对具有唯一值时,记录是唯一的。需要明确的是: CID = 1 和 PID = 10 的记录可以与 CID = 2 和 PID = 10 的记录共存(两家公司可能希望拥有使用相同标识符标记的产品,对吗?),因此 CID = 1 的记录也可以共存并且PID = 9。当然,同时具有CID=1 和PID=10 值的两条记录不能共存。我不想引入另一个具有唯一记录标识符的列,因为我希望应用这些规则而不创建检查完整性的 C# 层。 我希望这是可以理解的,我试图说清楚,但不知怎的我找不到词语来描述它。
Let us say we have a product catalog. Table has following fields:
CompanyID
and
ProductID
. I want the table primary key to be based on those two fields, so as a record is unique when its pair of CompanyID and ProductID fields have unique values. To be clear:
a record of CID = 1 and PID = 10 can coexist with a record of CID = 2 and PID = 10 (two companies may wish to have a product tagged with the same identifier, right?), so can a record of CID = 1 and PID = 9. Of course two records with both CID=1 and PID=10 values can not coexist. I do not want to introduce another column with unique record identifier, because I want these rules to be applied without creating a C# layer checking for integrity.
I hope this is understandable, i tried to be clear but I somehow can't find words to describe it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其中任何一个都适用于您的 PRODUCTS 表:
或
但如果您创建复合主键,则对该复合 PK 的所有外部引用也必须是复合的两列。例如,引用产品的订单需要两列:
但这对于查询和前端 GUI 代码来说会更简单:
我不确定您的意思
这些约束/索引可以在数据库本身中创建,并且数据库将强制执行这些规则;您的 C# 客户端程序不会强制执行这些规则,而只会在尝试违反规则时报告数据库生成的错误。第一种方法,产品1,您有一个单独的自动增量主键,为您提供了行的简单句柄,同时还强制执行您所需的两列唯一性规则。这是常见的做法。
Either of these would work for your PRODUCTS table:
or
But if you create a composite primary key, all foreign references to that composite PK will also have to be composite, two-columns. Orders, for example, referencing the product would require two columns:
but this would be simpler for queries and in your front-end GUI code:
I am not sure what you mean by
These constraints/indexes can be created in the database itself and the database would enforce the rules; your C# client program would not enforce these rules but would merely report errors generated by the database when attempts were made to violate the rules. The first approach, PRODUCTS1, where you have a separate autoincrementing primary key, gives you a simple handle to the row while also enforcing the two-column uniqueness rule you desired. It is common practice.
是的,两列上的主键可以满足您的要求。试试吧。
Yes, a primary key on two column does what you want. Just try it out.
是的,
PRIMARY KEY(CompanyID,ProductID)
,但为了正常工作,两列都不应该为空。Yes,
PRIMARY KEY(CompanyID,ProductID)
, although to properly work neither column should be nullable.是的,您可以将多个列作为主键。
在设计器中,选择两列,然后单击“设置主键”
Yes, you can have multiple columns as your primary key.
In the designer, select both columns and then click Set Primary Key
是的,键是表的一组属性。原则上,您可以在其中添加任意数量的列。
Yes, a key is a set of attributes of a table. In principle you can have as many columns in it as you like.