首页 > 解决方案 > 尝试添加外键会导致“第 1 行出现错误 1064”

问题描述

我正在尝试在 、 和 列中创建外键,nameaddress_idphone不断收到错误消息。

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 行的 '' 附近使用正确的语法

标签: mysqlsqldatabase-designforeign-keyscreate-table

解决方案


您的直接问题是 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)
);

推荐阅读