mysql combined unique keys

為{幸葍}努か 提交于 2019-12-18 13:00:53

问题


Is there way in MySQL to have two unique keys and connect them somehow?

for example if i have the following table and 'title'and 'store' are a unique keys

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

   | 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?


回答1:


You can define an index on multiple columns, e.g.:

CREATE UNIQUE INDEX arbitrary_index_name ON table_name (title, store);



回答2:


Yes. Instead of two separate unique constraints you should create a single unique constraint on both columns.

The CREATE INDEX syntax is:

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 documentation for more details on how to create indexes.




回答3:


You need a multi-column unique key.




回答4:


ALTER TABLE table_name ADD UNIQUE INDEX( title, store);




回答5:


Yes you can!

ALTER TABLE table_name DROP PRIMARY KEY;
ALTER TABLE table_name ADD PRIMARY KEY(title, store);


来源:https://stackoverflow.com/questions/12125727/mysql-combined-unique-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!