<>记·外键之创建、删除

今天学习的是多表联合查询不过首先需要创建一个外键,创建完不对又要删,但这就一时间难到了,查资料,最后解决了

<>外键创建步骤

* 从表要新建一个同名同类型的字段
ALTER TABLE table_name ADD 字段 字段属性
* 再把该字段加入外键
ALTER TABLE table_name ADD FOREIGN KEY(字段) REFERENCES 关联表名(关联字段);
需要注意的是以下几点:

* 外键创建必须是唯一性字段,否则会报错如下:
MariaDB [blog]> alter table article_easyui add constraint `userName` foreign
key `userName` references users_easyui(userName); ERROR 1064 (42000): You have
an error in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near 'references
users_easyui(userName)' at line 1
* 设置唯一性需要以下sql语句:
ALTER TABLEtable_nameADD UNIQUE(user_ame);
* 外键删除需要先删除约束constraint
ALTER TABLE table_name DROP FOREIGN KEYforeign_name;
<>外键删除步骤

* 查看 表内部的字段
show create table table_name;
查询结果如下: ------------------------------------------------+ | article_easyui |
CREATE TABLE `article_easyui` ( `article_id` int(11) unsigned NOT NULL,
`article_title` int(11) NOT NULL, `article_content` int(11) NOT NULL,
`article_timestamp` int(11) NOT NULL, `userName` varchar(16) NOT NULL, PRIMARY
KEY (`article_id`), KEY `userName` (`userName`), CONSTRAINT
`article_easyui_ibfk_1` FOREIGN KEY (`userName`) REFERENCES `users_easyui`
(`userName`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+----------------+--------------------------
*
删除约束
alter table article_easyui drop foreign key article_easyui_ibfk_1

*
删除字段
alter table article_easyui drop id;

* 引用 https://blog.csdn.net/weixin_41000825/article/details/79103252`
<https://blog.csdn.net/weixin_41000825/article/details/79103252%60>