简体   繁体   中英

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.

Instead of making the comp_owner_id, comp_name pair unique, those columns have simply both been marked as needing to be unique. What is the correct way of going about this?

I'm using MySQL 5.1 with InnoDB tables.

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

Something like

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

where you supply the index_name and table_name.

Could you paste your table definition here ? I think you should define primarykey with two columns like so PRIMARYKEY(col1,col2) ?

This is from MySQL doc:

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. Doing so only marks that single column as primary. You must use a separate PRIMARY KEY(index_col_name, ...) clause.

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