外键定义语法:
[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, …)
REFERENCES tbl_name (index_col_name, …)
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
该语法可以在 CREATE TABLE 和 ALTER TABLE 时使用,CONSTRAINT是一个约束标志,这个约束可以是主键、唯一键等各种键,如果指定CONSTRAINT symbol,则就使用这个 symbol 作为这些键的名字,否则,MYSQL会自动生成一个名字。
ON DELETE、ON UPDATE表示事件触发限制,可设参数:
RESTRICT(限制外表中的外键改动)
CASCADE(跟随外键改动)
SET NULL(设空值)
SET DEFAULT(设默认值)
NO ACTION(无动作,默认的)
例如:
create table student(
sid int primary key,
sname char(120),
sex char(120),
scourse char(120)
);
create table course(
cid int primary key,
cname char(120),
ccredit int
);
create table stucourse(
scid int primary key,
sid int,
cid int,
foreign key(sid) references student(sid),
foreign key(cid) references course(cid),
garde int not null
);
foreign key 里面的 sid 和 cid 是 stucourse 表里面定义的两个字段,后面的两个 sid 和 cid 是 student 表 和 course 表里面的