如何在MySQL中执行复合唯一性? [英] How can I enforce compound uniqueness in MySQL?
问题描述
我遇到了一个情况,我想确保表的复合元素是唯一的。例如:
I have run into a situation where I want to ensure that a compound element of a table is unique. For example:
Table (
id char(36) primary key,
fieldA varChar(12) not null,
fieldB varChar(36) not null
)
不要将fieldA和fieldB作为复合主键,因为它们经常更改,'id'用作整个系统的参考。
I don't want fieldA and fieldB to be a compound primary key, since they change frequently, and 'id' is used as a reference throughout the system.
fieldA和fieldB是它们本身并不独特,但它们的组合需要独特。因此,例如{{1,Matt,Jones} {2,David,Jones} {3,Matt,Smith}}将是有效数据,但{{1,Matt,Jones},{2,Matt,Jones }}不会。
fieldA and fieldB are not unique in and of themselves, but their combinations need to be unique. So for example, {{1, Matt, Jones}, {2, David, Jones}, {3, Matt, Smith}} would be valid data, but {{1, Matt, Jones}, {2, Matt, Jones}} would not be.
推荐答案
在表格定义中添加一个UNIQUE键:
Add a UNIQUE key to your table definition:
Table (
id char(36) primary key,
fieldA varChar(12) not null,
fieldB varChar(36) not null,
UNIQUE fieldA_fieldB (fieldA, fieldB)
)
这篇关于如何在MySQL中执行复合唯一性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!