MySqlWorkbench
进入MySQLWorkbench,输入密码,点击登录
创建一个写sql的文本,点击左上方的sql+,如图所示:
今天写一下设置外键约束:分为两种, 第一种:创建表的时候设置外键,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_nameN data_type);
举个例子:创建一个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语句的结构是: Alter table table_name add constraint constraint_name foreign key(col_name) references table_name2(col_name2);
3、删除设置的外键,用到的sql语句的结构是 Alter table table_name drop foreign key constraint_name
举个例子:将library数据库中的borrow_record表中的外键删除,sql语句为alter table borrow_record drop foreign key pk_reader_id;刷新数据库后,点击borrow_record表的右键,在单击table inspector 查看foreign keys这一栏,发现pk_reader_id这一行删除了,如图所示:
设置外键约束的前提是外键的数据类型必须和关联表的主键的数据类型一致
删除外键的时候,用的是设置的constraint_name