MySQL: Unique constraint on multiple fields [duplicate]

半世苍凉 提交于 2019-12-18 20:17:38

问题


I have two tables --> Variables (id, name) and Variable_Entries (id, var_id, value).

I want each variable to have a unique set of entries. If I make the value entry unique then a different variable won't be able to have that same value which is not right.

Is there some way to make the value column unique for identical var_id's?


回答1:


Yes:

alter table Variable_Entries add unique (var_id, value);

Now you have a unique constraint across var_id and value together. In other words, no occurrence of var_id and value can appear more than once.




回答2:


Yes, you can create a composite unique key:

ALTER TABLE variable_entries ADD UNIQUE (var_id, value);



回答3:


Add a unique key of Variable_Entries for the combined fields var_id/value.

Also, you should always use singular words for table names (user instead of users). Never use uppercase characters in the table name, because that will cause you a NIGHTMARE over different operating systems.



来源:https://stackoverflow.com/questions/2504007/mysql-unique-constraint-on-multiple-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!