MySql复合Varchar类型的唯一索引

时间:2017-11-25 03:10:48

标签: php mysql sql unique unique-index

以下是我的情况:

• I have a table of users <br><br>
• I have a table of movies <br><br>
• I have a table of user_movies that associates users to movies that stores a frequently changing "score" column on each record.<br><br>
• I need to be able to bulk update the user_movies table for speed and to do so I believe I need a unique index to be able to pull off bulk updates like this.<br><br>
• Considering each user_movie combination is unique, would it be possible to do 

(User_id--->) uid_mid (<----movie_id)作为唯一标识符?如果是这样,怎么会将现有的表转换成这个呢?

1 个答案:

答案 0 :(得分:0)

我想认为有一种方法可以为您的问题使用双列索引,但是......

我想回答原来的问题并假设你真的想将这些列合并为一个,我建议考虑以下内容:

ALTER TABLE user_movies ADD COLUMN new_id VARCHAR(250);

UPDATE user_moves SET new_id=CONCAT(CAST(user_id as CHAR(125)), LPAD(CAST(move_id as CHAR(125)),125,'0'));

CREATE UNIQUE INDEX myindex ON user_movies(new_id);

数字250和125当然是任意的,但是你想要它们足够大以适应你的实际ID。我填充第二个ID以确保它们是真正独特的(因为我们不希望user_id = 55 / movie_id = 66获得与user_id = 5 / movie_id = 566相同的ID)。