简体   繁体   English

列中的唯一值,但每个关联的外键仅唯一:MySQL

[英]unique values in a column but only unique for each associated foreign key : MySQL

I asked this question a couple of weeks ago. 我几周前问了这个问题 Between now and then, I've moved to MySQL, and the solution has sadly not transferred over. 从那时起,我搬到了MySQL,但遗憾的是该解决方案尚未转移。

Instead of making the comp_owner_id, comp_name pair unique, those columns have simply both been marked as needing to be unique. 并没有使comp_owner_id, comp_name对具有唯一性,而是仅将这些列都标记为需要唯一。 What is the correct way of going about this? 正确的解决方法是什么?

I'm using MySQL 5.1 with InnoDB tables. 我正在将MySQL 5.1与InnoDB表一起使用。

If you create a unique index on those columns that should create a constraint that the combination of columns is unique. 如果在这些列上创建唯一索引,则应该创建约束以使列的组合是唯一的。 See http://dev.mysql.com/doc/refman/5.1/en/create-index.html http://dev.mysql.com/doc/refman/5.1/en/create-index.html

Something like 就像是

CREATE UNIQUE INDEX <index_name> ON <table_name> (COMP_OWNER_ID, COMP_NAME);

where you supply the index_name and table_name. 您在其中提供index_name和table_name。

Could you paste your table definition here ? 您可以在此处粘贴表定义吗? I think you should define primarykey with two columns like so PRIMARYKEY(col1,col2) ? 我认为您应该使用两列定义主键,例如PRIMARYKEY(col1,col2)?

This is from MySQL doc: 这是从MySQL文档:

A PRIMARY KEY can be a multiple-column index. 主键可以是多列索引。 However, you cannot create a multiple-column index using the PRIMARY KEY key attribute in a column specification. 但是,您不能使用列规范中的PRIMARY KEY键属性创建多列索引。 Doing so only marks that single column as primary. 这样做仅将单列标记为主要。 You must use a separate PRIMARY KEY(index_col_name, ...) clause. 您必须使用单独的PRIMARY KEY(index_col_name,...)子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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