[CONSTRAINT <外键名>] FOREIGN KEY 字段名 [,字段名2,…]
REFERENCES <主表名> 主键列1 [,主键列2,…]
mysql>create table students (id int undesigned frimary key auto_increment not null,
->name varchar(20) not null,
->age tinyint unsigned default 0,
->height decimal(5,2),
->foregien key(name) reference class(name)
->);
#创建students表,对其中name字段设置外键约束,其主表为class表,students表中name的数据只能从class表中的name选取。
ALTER TABLE <数据表名> ADD CONSTRAINT <外键名>
FOREIGN KEY(<列名>) REFERENCES <主表名> (<列名>);
alter table students add foregien key(name) reference class(name);
#给students表中的name列设置外键,students表中name的数据只能从class表中的name选取。
ALTER TABLE <表名> DROP FOREIGN KEY <外键约束名>;
alter table students drop foregien fk_name;
#最后是外键约束名,不是设置外键的字段名
show create table <表名>;
#查看constraint后的内容,就是外键约束名
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。