简体   繁体   中英

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

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?

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.

Plan B: 2 tables, each with 3 columns. One talks about TV shows; one for movies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM