MySQL 外键错误。约束键错误
MySQL Foreign Key ERROR. Constraint key error
我无法将外键添加到现有 table。报错如下
Executing:
ALTER TABLE `sms`.`student_account`
ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE;
;
ALTER TABLE `sms`.`student_account`
ADD CONSTRAINT `student_id`
FOREIGN KEY (`student_id`)
REFERENCES `sms`.`student` (`student_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
SQL Statement:
ALTER TABLE `sms`.`student_account`
ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE
我已经编写了以下可用的架构。我建议不要对已用于该列的约束使用相同的名称 student_id
。我希望 fk_student_id
避免在某些时候出现歧义或冲突的风险。
create table `student_account` (
student_id int);
create table `student`(
student_id int primary key
);
✓
✓
ALTER TABLE `student_account`
ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE;
✓
ALTER TABLE `student_account`
ADD CONSTRAINT `student_id`
FOREIGN KEY (`student_id`)
REFERENCES `student` (`student_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;
✓
db<>fiddle here
我无法将外键添加到现有 table。报错如下
Executing:
ALTER TABLE `sms`.`student_account`
ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE;
;
ALTER TABLE `sms`.`student_account`
ADD CONSTRAINT `student_id`
FOREIGN KEY (`student_id`)
REFERENCES `sms`.`student` (`student_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
SQL Statement:
ALTER TABLE `sms`.`student_account`
ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE
我已经编写了以下可用的架构。我建议不要对已用于该列的约束使用相同的名称 student_id
。我希望 fk_student_id
避免在某些时候出现歧义或冲突的风险。
create table `student_account` ( student_id int); create table `student`( student_id int primary key );
✓ ✓
ALTER TABLE `student_account` ADD INDEX `student_id_idx` (`student_id` ASC) VISIBLE;
✓
ALTER TABLE `student_account` ADD CONSTRAINT `student_id` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`) ON DELETE RESTRICT ON UPDATE CASCADE;
✓
db<>fiddle here