1. 程式人生 > 其它 >mysql-DDL定義語言(create、drop、alter)-約束

mysql-DDL定義語言(create、drop、alter)-約束

一、約束包含:

  •      非空約束:not null
  •      唯一性約束:unique
  •      主鍵約束:primary key     primary key auto_increment,表示自增,從一開始,以一自增;  
  •      外來鍵約束:foreign key(子表約束欄位)  references 父表表名(父表約束欄位)
  •      檢查約束:check (mysql不支援;oracle支援)

1、非空約束:not null:非空約束:not null;只能列級約束,沒有表約束;not null 約束的欄位不能為null

  • drop table if exists t_vip;
  • create table t_vip(
  •      id int ,
  •     name varchar(255) not null
  •     );
  •     insert into t_vip (id,name) values(1,'zhangsan');
  •     insert into t_vip (id,name) values(2,'lisi');

2、唯一性約束:uniquqe:唯一性約束unique 約束欄位不能重複,但是可以為null

  • drop table if exists t_vip;
  • create table t_vip(
  •      id int ,
  •     name varchar(255) unique ,
  •     email varchar(255)
  •     );
  • 需求:name 和email 兩個欄位聯合起來具有唯一性!
  • create table t_vip(
  •      id int,
  •     name varchar(255) ,
  •     email varchar(255),
  •     unique(name,email)
  •     );

3、not null unique聯合使用:在mysql中,一個欄位同時被not null 和unique 約束的話;該欄位自動變成主鍵欄位(oracle中不一樣)!

  •  create table t_vip(
  •            id int,
  •            name varchar(255) not null unique,
  •            email varchar(255)    
  •     );

 

4、主鍵約束簡稱pk:primary key ( primary key auto_increment,表示自增,從一開始,以一自增;)

  • 1、術語: 主鍵約束;主鍵欄位:主鍵值;主鍵特徵:not null+ unique ;主鍵值不能為:null,同時也不能重複
  • 2、主鍵值分類:單一主鍵(列級)、複合主鍵(聯合使用表級)自然主鍵(使用較多推薦使用)
  • 3、主鍵值:是每一行記錄的唯一標識。 任何一張表都有主鍵,沒有主鍵表無效!一張表主鍵約束只能新增一個;
  •       建議使用型別:int、bigint、char;因為主鍵值是定長;
  • 4、如何給一張表新增主鍵約束:單一主鍵
  •   create table t_vip(
  •    id int primary key  auto_increment, //列級約束
  •    name varchar(255)
  •    );

 

5、外來鍵約束簡稱FK:fpreign key

  • 1、外來鍵約束語法:foreign key  (外來鍵:子表中和父表關聯欄位名) reference   父表表名(父表和子表關聯的欄位名)
  • 2、父表、子表:先建立父表在建立子表---先刪子表後刪父表;
  • 業務背景: 請設計資料庫表。來描述“班級和學生”的資訊
  •   drop table if exists t_student;
  •   drop table if exists t_class;
  •   create table t_class(
  •    cno int,
  •    cname varchar(255),
  •    primary key(cno)
  •   );
  •   create table t_student(
  •    sno int,
  •    sname varchar(255),
  •    classno int,
  •    foreign key(classno) references t_class(cno)//外來鍵約束語法;
  •   );