===设置主键约束 PRIMARY KEY
目的:
1、primary key 字段的值是不允许重复,且不允许NULL(UNIQUE + NOT NULL)
2、单列做主键
3、多列做主键(复合主键)
创建表
示例1:
表school.student6 方法一
mysql> create table student6(
id int primary key not null auto_increment,
name varchar(50) not null,
sex enum('male','female') not null default 'male',
age int not null default 18
);
Query OK, 0 rows affected (0.00 sec)
示例2:
表school.student6 方法一
mysql> create table student6(
id int primary key not null auto_increment,
name varchar(50) not null,
sex enum('male','female') not null default 'male',
age int not null default 18
);
Query OK, 0 rows affected (0.00 sec)
查询表结构
desc student6;
+-------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| sex | enum('male','female') | NO | | male | |
| age | int(11) | NO | | 18 | |
+-------+-----------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
![如图](https://img.haomeiwen.com/i15572377/beab11b095f1bd29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
插入数据
mysql> insert into student6 values (1,'alice','female',22);
mysql> insert into student6(name,sex,age) values
('jack','male',19),
('tom','male',23);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
查询表内容
mysql> select * from student6;
+----+-------+------+-----+
| id | name | sex | age |
+----+-------+------+-----+
| 1 | alice | female | 22 |
| 2 | jack | male | 19 |
| 3 | tom | male | 23 |
+----+-------+------+-----+
3 rows in set (0.00 sec)
(注意观察id列,并没有输入内容,自动增长。如果在此列插入空值呢?)
插入非法数据
MariaDB [company]> insert into student6(name,sex,age) values (3,'jack','male',19);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
![图示1](https://img.haomeiwen.com/i15572377/c40b3cbe6bee6929.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
主键设置了自动增长,再次尝试插入数据。成功(注意不要插入主键)
网友评论