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

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

    For adding unique index following are required:

    1) table_name
    2) index_name
    3) columns on which you want to add index

    ALTER TABLE  `tablename` 
    ADD UNIQUE index-name
    (`column1` ,`column2`,`column3`,...,`columnN`);
    

    In your case we can create unique index as follows:

    ALTER TABLE `votes`ADD 
    UNIQUE <votesuniqueindex>;(`user` ,`email`,`address`);
    
    0 讨论(0)
  • 2020-11-21 07:09

    MySql 5 or higher behaves like this (I've just tested):

    • you can define unique constraints involving nullable columns. Say you define a constraint unique (A, B) where A is not nullable but B is
    • when evaluating such a constraint you can have (A, null) as many times you want (same A value!)
    • you can only have one (A, not null B) pair

    Example: PRODUCT_NAME, PRODUCT_VERSION 'glass', null 'glass', null 'wine', 1

    Now if you try to insert ('wine' 1) again it will report a constraint violation Hope this helps

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

    Have you tried this ?

    UNIQUE KEY `thekey` (`user`,`email`,`address`)
    
    0 讨论(0)
  • 2020-11-21 07:15

    I do it like this:

    CREATE UNIQUE INDEX index_name ON TableName (Column1, Column2, Column3);
    

    My convention for a unique index_name is TableName_Column1_Column2_Column3_uindex.

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

    If You are creating table in mysql then use following :

    create table package_template_mapping (
    mapping_id  int(10) not null auto_increment  ,
    template_id int(10) NOT NULL ,
    package_id  int(10) NOT NULL ,
    remark      varchar(100),
    primary key (mapping_id) ,
    UNIQUE KEY template_fun_id (template_id , package_id)
    );
    
    0 讨论(0)
  • 2020-11-21 07:18
    ALTER TABLE `votes` ADD UNIQUE `unique_index`(`user`, `email`, `address`);
    
    0 讨论(0)
提交回复
热议问题