pp泉 2021-03-27 13:27 采纳率: 50%
浏览 72
已采纳

求大神看看,mysql主键和外键为什么没有关联

create database studentsdb;

alter database studentsdb character set utf8;

use studentsdb;

 

create table student_info(

student_id char(4) not null primary key,

student_name char(8) not null,

sex char(2),

birthday date,

address varchar(50));

 

create table curriculum(

class_id char(4) not null primary key,

class_name varchar(50),

credit int);

 

create table grade(

student_id char(4),

class_id char(4),

score int);

 

alter table grade add primary key(student_id,class_id);

 

alter table grade add constraint fk_student_id foreign key(student_id) references student_info(student_id) on delete cascade;

 

alter table grade add constraint fk_class_id foreign key(class_id) references curriculum(class_id) on delete cascade;

 

insert into student_info(student_id,student_name)values('1001','张三');

 

insert into curriculum(class_id)values('123');

前面把grade表的student_id和class_id都设为了外键,但是下面插入主键中没有的值为什么还是可以插入?

insert into grade(student_id,class_id,score)values('1002','456',85);

  • 写回答

3条回答 默认 最新

  • 沐川 2021-03-27 19:14
    关注

    增加两个索引:

    alter table grade add key (student_id);
    alter table grade add key (class_id);

    参考资料:https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html#foreign-key-restrictions

    MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

     

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀