简体   繁体   中英

MySQL Alter table add column that is unique together with another column

I have such a table:

+---------+--------------+------+-----+-------------------+-----------------------------+
| Field   | Type         | Null | Key | Default           | Extra                       |
+---------+--------------+------+-----+-------------------+-----------------------------+
| id      | int(11)      | NO   | PRI | NULL              | auto_increment              |
| url     | varchar(255) | YES  | UNI | NULL              |                             |
| ts      | timestamp    | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| content | longblob     | YES  |     | NULL              |                             |
| source  | varchar(255) | YES  |     | NULL              |                             |
| state   | int(11)      | NO   |     | 0                 |                             |
+---------+--------------+------+-----+-------------------+-----------------------------+

I'd like the id to stay the only PRIMARY KEY and I'd like to add field "VERSION" which will be unique.

What I want is to create unique pair (url, version) unique together but not separately. How can I do that? Should I add field version just like that, alter url so it's not unique and then add constraint?

Thanks in advance!

If what you're looking for is to store multiple versions of the same URL together in the table, then yes, what you need to do is:

  1. Drop the unique constraint on URL
  2. Add non-unique column version (assume integer here)
  3. Create unique constraint or index on (url, version). I would suggest an index since I think that should make the unique checks faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM