简体   繁体   中英

make a foreign key to unique index in mysql

products

 CREATE TABLE if NOT EXISTS `PRODUCTS` ( `ID` INT unsigned NOT NULL AUTO_INCREMENT, `COMPANY_ID` INT(10) unsigned NOT NULL, `PRODUCT_CODE` VARCHAR(5) NOT NULL, `PRODUCT_NAME` VARCHAR(15) NOT NULL, PRIMARY KEY (`ID`), UNIQUE INDEX UNIQUE_COMAPNY_UNIT_CODE (`COMPANY_ID`, `PRODUCT_CODE`) ) 

Services

 ALTER TABLE services ADD COLUMN `PRODUCT_CODE` VARCHAR(5), ADD FOREIGN KEY (`PRODUCT_CODE`) REFERENCES PRODUCTS(`PRODUCT_CODE`) ON DELETE CASCADE ON UPDATE CASCADE; 

but it always gives me this error when trying to make the upper foreign key missing index in the references table products ... any help how to make a product_code in services table refrences to product_code in products table ?

Foreign keys must reference indexes that start with the fields referenced, in the order referenced. To reference PRODUCT_CODE, you must have an index on (or starting with) PRODUCT_CODE.

Also, typically, you reference the PK of the table; if for no other reason than it minimizes the situations where cascades are needed. A product code is more likely to change than an auto incremented row identifier.

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