mysql combined unique keys

David picture David · Aug 25, 2012 · Viewed 24.5k times · Source

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?

Answer

Bugs picture Bugs · Aug 25, 2012

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

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