不多说,直接上干货!
(1)主键约束PRIMARY KEY
(2)每张数据表只能存在一个主键
(3)主键保证记录的唯一性
(4)主键自动为NOT NULL
(1)主键约束PRIMARY KEY
1 create table tb3( 2 id smallint unsigned auto_increment primary key, 3 username varchar(30) not null 4 );
注意:auto_increment必须和主键一起使用,但是这并不代表主键一定要和auto_increment一起使用主键可以写成PRIMARY KEY,也可以写成KEY。
(3)主键保证记录的唯一性
insert tb3(username) values(‘zhangshan‘); insert tb3(username) values(‘lisi‘); insert tb3(username) values(‘wangwu‘); insert tb3(username) values(‘lineng‘); select * from tb3;
create table tb4( id smallint unsigned key, username varchar(30) not null ); select columns from tb4;
insert tb4 values(3,‘zhaosi‘); insert tb4 values(9,‘dajiao‘); select * from tb4; insert tb4 values(9,‘xiaomeng‘);
mysql> insert tb4 values(3,‘zhaosi‘);
Query OK, 1 row affected (0.05 sec)
mysql> insert tb4 values(9,‘dajiao‘);
Query OK, 1 row affected (0.07 sec)
mysql> select * from tb4;
+----+----------+
| id | username |
+----+----------+
| 3 | zhaosi |
| 9 | dajiao |
+----+----------+
2 rows in set (0.00 sec)
mysql> insert tb4 values(9,‘xiaomeng‘);
ERROR 1062 (23000): Duplicate entry ‘9‘ for key 1
mysql>
时间: 2024-12-26 00:13:51