MySQL mysql组合唯一键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12125727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql combined unique keys
提问by David
Is there way in MySQL to have two unique keys and connect them somehow?
在 MySQL 中有没有办法拥有两个唯一的键并以某种方式连接它们?
for example if i have the following table and 'title'and 'store' are a unique keys
例如,如果我有下表,并且“title”和“store”是唯一键
id | category | title | price | store
1 | outdoors | fishing rod | 59.99 | wal-mart
2 | auto | Penzoil Oil | 9.99 | target
and i try to insert the following record. This new record would be ignored because the title is "fishing rod" AND the store is 'wal-mart' and there is an existing record with that title and store
我尝试插入以下记录。这条新记录将被忽略,因为标题是“fishing rod”并且商店是“wal-mart”,并且存在具有该标题和商店的现有记录
| outdoors | fishing rod | 30.99 | wal-mart
but if i attempted to insert the following record it would be accepted because there isn't a record that exists with the title of "fishing rod" and store of "target"
但是,如果我尝试插入以下记录,它将被接受,因为不存在标题为“钓鱼竿”且存储为“目标”的记录
| outdoors | fishing rod | 30.99 | target
is this possible with just MySQL?
这可能只用 MySQL 吗?
回答by Bugs
You can define an index on multiple columns, e.g.:
您可以在多个列上定义索引,例如:
CREATE UNIQUE INDEX arbitrary_index_name ON table_name (title, store);
回答by Mark Byers
Yes. Instead of two separate unique constraints you should create a single unique constraint on both columns.
是的。您应该在两列上创建一个唯一约束,而不是两个单独的唯一约束。
The CREATE INDEX
syntax is:
该CREATE INDEX
语法是:
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
[index_type]
ON tbl_name (index_col_name,...)
[algorithm_option | lock_option] ...
For your example it would look something like this:
对于您的示例,它看起来像这样:
CREATE UNIQUE INDEX index_name ON tbl_name (title,store);
You will also have to drop the two incorrect unique indexes that you created.
您还必须删除您创建的两个不正确的唯一索引。
See the documentationfor more details on how to create indexes.
有关如何创建索引的更多详细信息,请参阅文档。
回答by Shi
You need a multi-column unique key.
您需要一个多列唯一键。
回答by shyam sasi
ALTER TABLE table_name
ADD UNIQUE INDEX( title
, store
);
ALTER TABLE table_name
ADD UNIQUE INDEX( title
, store
);
回答by Chris Forrence
Yes you can!
是的你可以!
ALTER TABLE table_name DROP PRIMARY KEY;
ALTER TABLE table_name ADD PRIMARY KEY(title, store);