美文网首页
SQL的约束

SQL的约束

作者: lupinwu | 来源:发表于2017-03-12 22:48 被阅读0次

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

    约束分类

    |约束类型 |主键 |默认值 |唯一 |外键 |非空
    |-
    |关键字 |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)
    

    相关文章

      网友评论

          本文标题:SQL的约束

          本文链接:https://www.haomeiwen.com/subject/qavxnttx.html