SQL的约束

约束是一种限制,它通过对表的行或列的数据做出限制,来确保表的数据的完整性、唯一性。

约束分类

|约束类型 |主键 |默认值 |唯一 |外键 |非空
|-
|关键字 |PRIMARY KEY |DEFAULT |UNIQUE |FOREIGN KEY |NOT NULL

  • 创建实验用数据表(SQL3)
CREATE TABLE department
(
  dpt_name   CHAR(20) NOT NULL,
  people_num INT(10) DEFAULT '10',
  CONSTRAINT dpt_pk PRIMARY KEY (dpt_name)
 );

CREATE TABLE employee
(
  id      INT(10) PRIMARY KEY,
  name    CHAR(20),
  age     INT(10),
  salary  INT(10) NOT NULL,
  phone   INT(12) NOT NULL,
  in_dpt  CHAR(20) NOT NULL,
  UNIQUE  (phone),
  CONSTRAINT emp_fk FOREIGN KEY (in_dpt) REFERENCES department(dpt_name)
 );

CREATE TABLE project
(
  proj_num   INT(10) NOT NULL,
  proj_name  CHAR(20) NOT NULL,
  start_date DATE NOT NULL,
  end_date   DATE DEFAULT '2015-04-01',
  of_dpt     CHAR(20) REFERENCES department(dpt_name),
  CONSTRAINT proj_pk PRIMARY KEY (proj_num,proj_name)
 );
  • 加载实验数据
mysql> source ~/mysql/SQL3/MySQL-03-01.sql

mysql> show tables;
+------------------------+
| Tables_in_mysql_shiyan |
+------------------------+
| department             |
| employee               |
| project                |
+------------------------+
3 rows in set (0.00 sec)
    原文作者:lupinwu
    原文地址: https://www.jianshu.com/p/c0242684ecae
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞