标签:create exists ica not mod article 合约 row extra
能唯一确定一张表中的记录,也就是我们通过给某个字段添加约束,就可以使得改字段不重复且不为空。
create table test1(
id int primary key,
name varchar(20) not null
);
create table test2(
id int,
name varchar(20),
password varchar(20),
primary key(id,name)
);
mysql> desc test2;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(20) | NO | PRI | NULL | |
| password | varchar(20) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
3 rows in set
insert into test2 values(1,‘张三‘,‘000‘);
insert into test2 values(1,‘李四‘,‘000‘);
insert into test2 values(2,‘张三‘,‘000‘);
Query OK, 1 row affected
insert into test2 values (null,‘xiaoming‘,‘000‘);
1048 - Column ‘id‘ cannot be null
create table test3(
id int,
name varchar(20)
);
alter table test3 add primary key (id);
或者:
alter table test3 modify id int primary key;
alter table test3 drop primary key;
约束的字段不为空,当只约束一个字段的时候,显示的是UNI,若修饰多个字段,显示的是MUL
create table test4(
id int,
name varchar(20),
unique(name)
);
create table test4(
id int,
name varchar(20) unique
);
create table test4(
id int,
name varchar(20)
);
alter table test4 add unique(name);
或者
alter table test4 modify name varchar(20) unique;
mysql> desc test4;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | UNI | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set
create table test4(
id int,
name varchar(20),
unique (id,name)
);
mysql> desc test4;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | MUL | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set
insert into test4 values (1,‘lisi‘);
insert into test4 values (2,‘lisi‘);
即使是联合约束,相当于查找汉字的首字母和具体拼写一样,这种联合约束,只能直接删除主要的约束(首字母),并且删除掉这个约束后,所有的约束均删除了 联合约束只能删除主要约束,并且主要约束删除了,所有约束都删除了
alter table test4 drop index name;
1091 - Can‘t DROP ‘name‘; check that column/key exists
alter table test4 drop index id;
Query OK, 2 rows affected
Records: 2 Duplicates: 0 Warnings: 0
参考资料:
https://www.bilibili.com/video/av39807944/?p=12 https://blog.csdn.net/nanaMasuda/article/details/52543177
19、约束之间的比较:主键约束、联合约束、唯一约束、外键约束
标签:create exists ica not mod article 合约 row extra
原文地址:https://www.cnblogs.com/Stephanie-boke/p/11675198.html