I have a table which contains meta data for users. There are 4 fields…
`ID`,`meta_name`,`meta_value`,`user_id`
I want to store emails in this table. Naturally these must be unique. However I want to store other data in this table as well, where the data does not need to be unique. Is there any way I can restrict 'meta_value' to be unique, only if 'meta_name' is equal to ’email’?
By means of MySQL’s contraints – no.
However you can use insert/update trigger that verifies uniqueness of the data and forbids illegal operations.
Here is a draft of insert trigger (You can play with it here: http://sqlfiddle.com/#!2/5c9e3):