How do I specify unique constraint for multiple columns in MySQL?

后端 未结 14 1980
庸人自扰
庸人自扰 2020-11-21 06:50

I have a table:

table votes (
    id,
    user,
    email,
    address,
    primary key(id),
);

Now I want to make the columns user

相关标签:
14条回答
  • 2020-11-21 07:18

    Multi column unique indexes do not work in MySQL if you have a NULL value in row as MySQL treats NULL as a unique value and at least currently has no logic to work around it in multi-column indexes. Yes the behavior is insane, because it limits a lot of legitimate applications of multi-column indexes, but it is what it is... As of yet, it is a bug that has been stamped with "will not fix" on the MySQL bug-track...

    0 讨论(0)
  • 2020-11-21 07:19

    this tutorial works for me

    ALTER TABLE table_name
    ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);
    

    https://www.mysqltutorial.org/mysql-unique-constraint/

    0 讨论(0)
  • 2020-11-21 07:21

    If you want to avoid duplicates in future. Create another column say id2.

    UPDATE tablename SET id2 = id;
    

    Now add the unique on two columns:

    alter table tablename add unique index(columnname, id2);
    
    0 讨论(0)
  • 2020-11-21 07:22

    First get rid of existing duplicates

    delete a from votes as a, votes as b where a.id < b.id 
    and a.user <=> b.user and a.email <=> b.email 
    and a.address <=> b.address;
    

    Then add the unique constraint

    ALTER TABLE votes ADD UNIQUE unique_index(user, email, address);
    

    Verify the constraint with

    SHOW CREATE TABLE votes;
    

    Note that user, email, address will be considered unique if any of them has null value in it.

    0 讨论(0)
  • 2020-11-21 07:25

    I have a MySQL table:

    CREATE TABLE `content_html` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `id_box_elements` int(11) DEFAULT NULL,
      `id_router` int(11) DEFAULT NULL,
      `content` mediumtext COLLATE utf8_czech_ci NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `id_box_elements` (`id_box_elements`,`id_router`)
    );
    

    and the UNIQUE KEY works just as expected, it allows multiple NULL rows of id_box_elements and id_router.

    I am running MySQL 5.1.42, so probably there was some update on the issue discussed above. Fortunately it works and hopefully it will stay that way.

    0 讨论(0)
  • 2020-11-21 07:27

    This works for mysql version 5.5.32

    ALTER TABLE  `tablename` ADD UNIQUE (`column1` ,`column2`);
    
    0 讨论(0)
提交回复
热议问题