Best way to create Unique index in MYSQL on two columns when one column can contain empty values

user6631314 :

I would like to create a unique index on two columns, one of which always has a value but another where the value is often 0 by default.

In the following example, userid 22 liked 2 TV shows and 3 movies. I want to prevent a case where the user would like the same tv show or movie twice. However, I can't make it UNIQUE to userid and movieid or userid and tvshowid, as there are numerous cases where the userid is paired with 0 when the like is for a TV show.

Likes
id|userid|movieid|tvshowid
1|22|0|33
2|22|0|34
3|22|66|0
4|22|67|0
5|22|68|0

I could change all the 0s to NULLs but NULLS tend to create problems on the client.

What is the best way to handle creating a unique index on two columns when one has multiple empty values in it?

If it requires changing all the 0s to NULLs, is there an efficient MYSQL statement to do this?

Bill Karwin :

Change zeroes to NULLs:

UPDATE Likes SET movieid = NULL WHERE movieid = 0;
UPDATE Likes SET tvshowid = NULL WHERE tvshowid = 0;

Create two unique keys, one for movies and one for tvshows.

ALTER TABLE Likes
  ADD UNIQUE KEY (userid, movieid),
  ADD UNIQUE KEY (userid, tvshowid);

I don't know what you mean by NULLs causing problems on the client. Any client that can use SQL should be able to handle NULLs.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371634&siteId=1