手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

对表的字段设置外键的sql

时间:2024-10-29 21:14:59

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_record表的reader_id设置为外键,sql语句为alter table 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
© 手抄报圈