建立表users
CREATE TABLE users(
id int AUTO_INCREMENT PRIMARY KEY,
authority char(20) NOT NULL,
operationid char(10) NOT NULL,
status char(10) NOT NULL,
username char(20) NOT NULL,
password char(20) NOT NULL,
realname char(20) NOT NULL,
tel char(20) NOT NULL,
department char(30) NOT NULL,
checkintime date NOT NULL,
resigntime date NULL);
注意:为users表的authority和department两个字段建立外键约束,当然啦,前提是先建立好这连个表。
OK,先 建立authority表吧!
--创建用户权限表
CREATE TABLE authority(
name char(20) NOT NULL PRIMARY KEY);
接着,我们再来建立department表:
--创建用户所属部门表
CREATE TABLE department(
name char(30) NOT NULL PRIMARY KEY);
好了,现在开始建立外键约束吧!
--给users表的部门(department)和权限(authority)添加外键
Alter table users add foreign key(department) references department(name) on delete restrict on update cascade; |
Alter table users add foreign key(authority) references authority(name) on delete restrict on update cascade;
好了,问题来了,建立约束之后,authority和department的内容是限制更改的,如果想改变的话,怎么办?先修改users表中与authority和department对应的信息,之后就可以修改了。什么意思呢?
上图吧!
insert into authority(name)values('总检员');
insert into authority(name)values('打包员');
insert into authority(name)values('操作员');
insert into authority(name)values('管理员');
insert into department(name)values('管理部');
insert into department(name)values('工程部');
insert into users(authority,operationid,status,username,password,realname,tel,department) values('管理员','12345','离职','admin','123456','章撒','787878','管理部');
看到了吗?建立好authority与department后,才能在users中添加信息,而且特别注意的是,在users表中的authority和department这两个字段的信息,必须与外键表authority和department中的信息保持一致才不会出错,否则的话,插入会失败!!!
如果想要修改外键authority或者department中的内容,前提是要在users表中将authority和department这两个字段的信息修改,也就是与外键脱离才行,否则也是修改失败!!
OK,就这么多了,抓紧试一下吧!
补充个小知识:
-
清空数据表:truncate table **;
-
删除数据表:delete from table_name WHERE name = '***';
mysql中Unicode编码,1个字符=2个字节,汉字=4个字节,