I have the following two tables:
CREATE TABLE `table1` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`CODE` varchar(30) COLLATE utf8_bin NOT NULL,
`LANG` varbinary(30) NOT NULL,
`NAME` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`ID`),
KEY `NewIndex1` (`CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
and
CREATE TABLE `table2` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TABLE1_CODE` varchar(30) NOT NULL,
`SOME_ADD` varchar(30) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
and I am trying to make a reference with:
alter table `factorydb`.`table2` add constraint `FK_table2` FOREIGN KEY (`TABLE1_CODE`) REFERENCES `table1` (`CODE`)
I get the error:
Can't create table 'factorydb.#sql-70c_306' (errno: 150)
The idea is to deal with language entries in my tables, so that I will have some values in table1 as
ID | CODE | LANG | NAME
1 CARCODE EN Car
2 CARCODE DE Auto
And I want to make a reference to the CODE in table1 as for me both CARCODE values are valid, only depending on the language settings.
I am doing it wrong?
All help is appreciated.
Both the columns in the foreign key, must be the same type, length AND collation.
Btw, you really want to prefer setting a foreign key on integers instead of varchars, it's much faster joining and takes less space
The problem is that the two linked columns are not the same type:
Table1
---------
`CODE` varchar(30) COLLATE utf8_bin NOT NULL,
Table2
---------
`SOME_ADD` varchar(30) DEFAULT NULL,
//This column does not have the utf8_bin collation !
You need to make sure the definition is exactly the same.
像你这样更改你的FK列
TABLE1_CODE varchar(30) COLLATE utf8_bin NOT NULL
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.