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

后端 未结 14 2039
庸人自扰
庸人自扰 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: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.

提交回复
热议问题