对表的字段设置外键的sql

2025-04-19 04:08:37

1、进入MySQLWorkbench,输入密码,点击登录

对表的字段设置外键的sql

2、创建一个写sql的文本,点击左上方的sql+,如图所示:

对表的字段设置外键的sql

3、今天写一下设置外键约束:分为两种,第一种:创建表的时候设置外键,sql语句的结构是:Create table table_name(Col_name1 data_type,Col_name1 data_type,constraint constraint_name foreign key(col_name) references table_name2(col_name2),......Col_nameNdata_type);

4、举个例子:创建一个return娄多骋能_record表,其中borrow_id为外键,sql语句为use library; /*选择数据库*/create table return_record(return_id char(9),borrow_id char(6),constraint pk_borrow_id foreign key(borrow_id) references borrow_record(borrow_id),return_date date);刷新数据库后,左边library数据库中就有return_record表,接着查看一下表结构,borrow_id是否为外键,语句为:describe return_record;如图所示:

对表的字段设置外键的sql
对表的字段设置外键的sql

5、第二种:对已创建的表设置外键,sql语句的结构是:Alter table table_name add constraint constraint_name foreign key(col_name)references table_name2(col_name2);

6、举个例子:将borrow_re罕铞泱殳cord表的reader_id设置为外键,sql语句为alter tabl髫潋啜缅e borrow_record add constraint pk_reader_id foreign key(reader_id)references reader(reader_id);着查看一下表结构,reader_id是否为外键,语句为:describeborrow_record;如图所示:

对表的字段设置外键的sql
对表的字段设置外键的sql

7、删除设置的外键,用到的sql语句的结构是Alter table table_name drop foreign key constraint_name

8、举个例子:将library数据库中的borrow_record表中的外键删除,sql语句为alter table borrow_record drop foreign key pk_reader_id;刷新数据库后,点击borrow_record表的右键,在单击table inspector查看foreign keys这一栏,发现pk_reader_id这一行删除了,如图所示:

对表的字段设置外键的sql
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢