views:

5109

answers:

4

I have a table:

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

Now I want to make the columns user, email, address unique (together).

How do I do this in MySql?

Thanks in advance.

  • Of course the example is just... an example. So please don't worry about the semantics.
+12  A: 
alter table votes add unique index(user, email, address);
jonstjohn
A: 

Have you tried this ?

UNIQUE KEY `thekey` (`user`,`email`,`address`)
Erick
I tried this, but it doesn't seem to work. I will try again.
Niyaz
+1  A: 

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...

niksoft
Two points of clarification: 1) this behavior does not hold for `ENGINE BDB`, and, 2) this is *documented* behavior, although, IMHO, not documented overtly enough given how surprising/unpleasant it can be. See MySQL bug 25544 http://bugs.mysql.com/bug.php?id=25544 for a discussion.
pilcrow
A: 

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 accepted, 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.

Frodik