gpt4 book ai didi

mysql - 错误代码 1215 : Cannot add foreign key constraint

转载 作者:行者123 更新时间:2023-11-29 21:16:29 24 4
gpt4 key购买 nike

我尝试创建外键,但显示错误

"Error Code 1215 : Cannot add foreign key constraint "

我尝试修复它,但不起作用。

这是我的脚本:

drop database if exists `manage_Student`;

create database if not exists `manage_Student` default character set utf8;

use `manage_Student`;

drop table if exists `students`;

create table if not exists `students` (
`id` smallint(8) not null,
`name` varchar(50) not null,
`id_pos` smallint (10) not null,
`address` varchar(50),
`gender` varchar(7) check (gender in ('male', 'female')),
primary key (`id`),
constraint fk_stupos foreign key (`id_pos`) references `position` (`id_pos`)

) engine = InnoDB default char set = utf8;

drop table if exists `position`;

create table if not exists `position` (
`id_pos` smallint (10) not null,
`position` varchar (50),
primary key (`id_pos`)
) engine = InnoDB default char set = utf8;

最佳答案

只需先创建position 表即可。它需要先存在,然后才能将其用于外键约束。

Here是一个 SQL Fiddle。

还值得注意的是:您对性别有一个检查约束。 MySQL 接受 check 约束的语法。但是,它实际上并没有做任何事情。这是为了提高与其他数据库的兼容性。

如果您确实想检查这些值,则需要使用性别引用表(以及另一个外键约束)或enum类型。

关于mysql - 错误代码 1215 : Cannot add foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35898427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com