简体   繁体   English

MySQL无法创建表(错误号:150)

[英]MySQL Can't create table (errno: 150)

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 我的想法是处理我的表中的语言条目,这样我将在table1中有一些值作为

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. 我想在table1中引用CODE,因为对我来说两个CARCODE值都是有效的,只取决于语言设置。

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 顺便说一下,你真的希望在整数而不是varchars上设置外键,加入速度要快得多,占用空间更少

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 

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

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