mysql --键表约束

--mysql 键表约束,sql

--主键约束;
它能够唯一确定一张表中的一条记录,也就是我们通过给某个字段添加约束,就可以使得该字段不重复,且不为空。
有且只有一个

create table user (
id int primary key,
name varchar(20)
);

mysql> describe user;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> insert into user values(1,‘zhangsan‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into user values(1,‘zhangsan‘);
ERROR 1062 (23000): Duplicate entry ‘1‘ for key ‘user.PRIMARY‘
mysql>

mysql> insert into user values(1,‘zhangsan‘);
ERROR 1062 (23000): Duplicate entry ‘1‘ for key ‘user.PRIMARY‘
mysql> insert into user values(2,‘zhangsan‘);
Query OK, 1 row affected (0.00 sec)

mysql> select * from user;
+----+----------+
| id | name |
+----+----------+
| 1 | zhangsan |
| 2 | zhangsan |
+----+----------+
2 rows in set (0.00 sec)

mysql>

mysql> insert into user values(null,‘zhangsan‘);
ERROR 1048 (23000): Column ‘id‘ cannot be null
mysql>

--联合主键;
--只要联合主键值加起来不重复就可以,也不可以为空;
mysql> create table user2(
-> id int,
-> name varchar(20),
-> password varchar(20),
-> primary key(id,name)
-> );
Query OK, 0 rows affected (0.01 sec)

mysql> select * from user2;
+----+----------+----------+
| id | name | password |
+----+----------+----------+
| 1 | lisi | 234 |
| 1 | zhangsan | 123 |
| 2 | zhangsan | 123 |
+----+----------+----------+
3 rows in set (0.00 sec)

 


--自增约束
mysql> create table user3(
-> id int primary key auto_increment,
-> name varchar(20)
-> );
Query OK, 0 rows affected (0.01 sec)

mysql> insert into user3 (name) values(‘zhangsan‘);
Query OK, 1 row affected (0.01 sec)

mysql> select * from user3;
+----+----------+
| id | name |
+----+----------+
| 1 | zhangsan |
+----+----------+
1 row in set (0.00 sec)
mysql> insert into user3 (name) values(‘zhangsan‘);
Query OK, 1 row affected (0.00 sec)

mysql> select * from user3;
+----+----------+
| id | name |
+----+----------+
| 1 | zhangsan |
| 2 | zhangsan |
+----+----------+
2 rows in set (0.00 sec)

--> 就是自我增长


--外键约束;

--唯一约束;

--非空约束;

--默认约束;

mysql --键表约束

上一篇:MySQL EXTRACT() 函数


下一篇:SpringBoot整合JDBC、Druid数据源与Mybatis、SpringData JPA