mysql - 尝试添加外键会导致“第 1 行出现错误 1064”
问题描述
我正在尝试在 、 和 列中创建外键,name
但address_id
我phone
不断收到错误消息。
mysql> create table driver(driver_id int(64) not null primary key,name varchar(100) not null,phone varchar(20) not null);
mysql> describe driver;
+-----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+-------+
| driver_id | int(64) | NO | PRI | NULL | |
| name | varchar(100) | NO | | NULL | |
| phone | varchar(20) | NO | | NULL | |
+-----------+---------------+------+-----+---------+-------+
mysql> create table customer(customer_id int(10) not null,name varchar(100) not null,age int(5) not null,address_id int(64) not null,phone varchar(20) not null,primary key(customer_id),foreign key(name) references driver(name);
ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '' 附近使用正确的语法
解决方案
您的直接问题是 parent 和 children 列必须具有相同的 datatype和 length。因此,您需要将name
子表中列的长度与父表(或相反)对齐:截至目前, on is isvarchar(100)
和 other is varchar(50)
。
但即便如此,从设计的角度来看,外键看起来并不好:为什么要引用驱动程序name
?尽管 MySQL 允许这样做(前提是您在父列上创建索引),但这不允许客户唯一标识驱动程序,这会质疑外键的相关性。我建议改为引用主键:
create table customer(
customer_id int(10) not null,
driver_id int not null,
age int(5) not null,
address_id int(64) not null,
phone varchar(20) not null,
primary key(customer_id),
foreign key(driver_id) references driver(driver_id)
);
推荐阅读
- r - map_dfr 函数将向量绑定到矩阵并并行运行的类比是什么?
- python - 如果将带有 None 值的 *args 传递给 namedtuple 对象,则会丢失所需的位置参数
- javascript - 标签按下时的焦点问题
- c# - 什么是检查字符串变量值是否是 C# 中一组指定值之一的智能方法?
- selenium - 通过 jenkins 从 TestNg 文件运行测试
- javascript - 如何知道用户是否从 facebook 或 WhatsApp 或 PHP 中的任何其他网站重定向(或来自)
- soap - 如何在 IBMi 上运行的 Liberty 上启用 SOAP 跟踪
- javascript - 定期刷新 Django 模板中的占位符和画布标签
- sql - Oracle 空值有时符合任何规则
- javascript - 如果单击已附加的 div 之一,如何获取值?