MySQL 外键 ON DELETE SET NULL 检查数据类型错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18807419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:50:51  来源:igfitidea点击:

MySQL foreign key ON DELETE SET NULL check data types error

mysqlsqlinnodb

提问by Maarten de Graaf

I'm working on a normalised database, to be secure I wanted to use foreign keys.

我正在开发一个规范化的数据库,为了安全起见,我想使用外键。

My database:

我的数据库:

CREATE TABLE `names` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `name_2` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_id` (`name_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The command:

命令:

ALTER TABLE  `names` ADD FOREIGN KEY (  `name` ) REFERENCES  `temp`.`users` (
`name_id`
) ON DELETE SET NULL ON UPDATE CASCADE ;

The response (error):
Error creating foreign key on name (check data types)

响应(错误):
在名称上创建外键时出错(检查数据类型)

So, how to fix this?

那么,如何解决这个问题?

回答by peterm

The error is self explanatory. Namein namestable is of type varchar(250)whereas name_idin userstable is of type int(11).

该错误是不言自明的。Namein namestable 是 type ,varchar(250)name_idin userstable 是 type int(11)

But I believe you meant to have an FK all the way around in userstable referencing namestable.

但是我相信您打算在users表引用names表中一直使用 FK 。

ALTER TABLE users
ADD FOREIGN KEY (name_id) REFERENCES names (id) 
  ON DELETE SET NULL ON UPDATE CASCADE; 

Here is SQLFiddledemo

这是SQLFiddle演示

回答by Mihai

Both keys have to be the same type and length,you have varchar and int.

两个键必须是相同的类型和长度,你有 varchar 和 int。

Here is what you want:

这是你想要的:

ALTER TABLE  `names` ADD FOREIGN KEY (  `id` ) REFERENCES  `users` (
`name_id`)