表的约束
Posted cmja
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表的约束相关的知识,希望对你有一定的参考价值。
约束条件 说明
PRIMARY KEY 主键约束,用于唯一标识对应的记录
FOREIGN KEY 外键约束
NOT NULL 非空约束
UNIQUE 唯一性约束
DEFAULT 默认值约束,用于设置字段的默认值
PRIMARY KEY 主键约束,用于唯一标识对应的记录
FOREIGN KEY 外键约束
NOT NULL 非空约束
UNIQUE 唯一性约束
DEFAULT 默认值约束,用于设置字段的默认值
多字段主键指的是多个字段组合而成的主键(PRIMARY KEY (字段名1,字段名2,……字段名n)
)
mysql> CREATE TABLE exam_1
->
-> (
-> stu_id INT,
-> course_id INT,
-> grade FLOAT,
-> PRIMARY KEY(stu_id,course_id)
-> );
Query OK, 0 rows affected
mysql> DESC exam_1;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| stu_id | int(11) | NO | PRI | 0 | |
| course_id | int(11) | NO | PRI | 0 | |
| grade | float | YES | | NULL | |
+-----------+---------+------+-----+---------+-------+
3 rows in set
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| stu_id | int(11) | NO | PRI | 0 | |
| course_id | int(11) | NO | PRI | 0 | |
| grade | float | YES | | NULL | |
+-----------+---------+------+-----+---------+-------+
3 rows in set
使用AUTO_INCREMENT设置表字段值自动增加(字段名 数据类型 AUTO_INCREMENT;
)
mysql> CREATE TABLE exam_2
-> (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> stu_id INT UNIQUE,
-> grade FLOAT DEFAULT 0
-> );
Query OK, 0 rows affected
)
mysql> CREATE TABLE exam_2
-> (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> stu_id INT UNIQUE,
-> grade FLOAT DEFAULT 0
-> );
Query OK, 0 rows affected
mysql> DESC exam_2;
+--------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| stu_id | int(11) | YES | UNI | NULL | |
| grade | float | YES | | 0 | |
+--------+---------+------+-----+---------+----------------+
3 rows in set
mysql> CREATE TABLE exam_3
-> (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> stu_id INT UNIQUE,
-> grade FLOAT
-> );
Query OK, 0 rows affected
-> (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> stu_id INT UNIQUE,
-> grade FLOAT
-> );
Query OK, 0 rows affected
mysql> DESC exam_3;
+--------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| stu_id | int(11) | YES | UNI | NULL | |
| grade | float | YES | | NULL | |
+--------+---------+------+-----+---------+----------------+
3 rows in set
+--------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| stu_id | int(11) | YES | UNI | NULL | |
| grade | float | YES | | NULL | |
+--------+---------+------+-----+---------+----------------+
3 rows in set
以上是关于表的约束的主要内容,如果未能解决你的问题,请参考以下文章