在MariaDB中错误地形成了外键约束

时间:2018-05-06 11:40:24

标签: mysql mariadb

这是我的sql代码,每次我按命令执行它都会给我一个错误,任何人都可以告诉我这里缺少什么?它给了我 “外键约束形成错误”错误。任何帮助都是极好的。

Create table course (course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0) check (credits > 0), primary key (course_id), foreign key (dept_name) references department on delete set null );

这是参考表:

create table department
    (dept_name      varchar(20), 
     building       varchar(15), 
     budget             numeric(12,2) check (budget > 0),
     primary key (dept_name)
    );

1 个答案:

答案 0 :(得分:1)

参见文档:

  

Foreign Keys

     

...

[CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

reference_option:
    RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
     

...

示例:

create table if not exists course (
  course_id varchar(8),
  title varchar(50),
  dept_name varchar(20),
  credits numeric(2,0) check (credits > 0),
  primary key (course_id),
  foreign key (dept_name)
  -- references department on delete set null
  references department (dept_name) on delete set null
);

请参阅dbfiddle