Yes, MySQL provides the ability to do this.
ALTER TABLE MyTable ADD UNIQUE KEY `my_unique_key` (`group_id`, `user_id`)
I donโt know what you are using this table for, but it looks like this unique key can be a strong candidate for the primary key of the table. The primary key is also automatically a unique key. If you decide to make it the primary key, do the following:
ALTER TABLE MyTable ADD PRIMARY KEY (`group_id`, `user_id`)
(If you get an error that there is already a primary key, enter ALTER TABLE MyTable DROP PRIMARY KEY and repeat the above command.)
Edit: In response to user comment
You cannot have multiple rows with the same non- NULL values โโfor columns covered by a unique key. So you cannot have two lines where group_id = 0 AND user_id = 5 , for example. 0 is the value. But if you make one or both columns null, you can have multiple rows that are identical with positioning NULL s. Thus, you can have two (or more) lines where group_id IS NULL AND user_id = 1234 .
Proviso: The above is true for commonly used MySQL storage systems (MyISAM and InnoDB). MySQL has storage mechanisms in which NULL treated as a unique value, but you probably don't use them.
If you make one or both columns null, then your unique key cannot be a primary key - the primary key must be in NOT NULL columns.
Suppose you make this key your primary key, and now you want to enable NULL in the group_id column. I do not know what data type group_id is at the moment; I assume this is now INT UNSIGNED NOT NULL , but you will have to change below if it is not. You can no longer use this key as the primary key. Here is the command you can run to make the necessary changes:
ALTER TABLE MyTable DROP PRIMARY KEY, MODIFY group_id INT UNSIGNED, ADD UNIQUE KEY `my_unique_key_with_nulls` (`group_id`, `user`)
Hammerite Sep 26 '10 at 16:11 2010-09-26 16:11
source share