1. 程式人生 > >約束條件

約束條件

port 默認 查看 values 條件 update 全局 一個表 alt

作用:用於保證數據的完整性和一致性

包含:

PRIMARY KEY (PK)    標識該字段為該表的主鍵,可以唯一的標識記錄
FOREIGN KEY (FK)    標識該字段為該表的外鍵
NOT NULL    標識該字段不能為空
UNIQUE KEY (UK)    標識該字段的值是唯一的(唯一性約束)
AUTO_INCREMENT    標識該字段的值自動增長(整數類型,而且為主鍵)
DEFAULT    為該字段設置默認值

UNSIGNED 無符號
ZEROFILL 使用0填充
------------------------------------------------------
主鍵在創建後默認是not null
但不是顯示的是 not null的都是主鍵,有僅僅只是設置的非空。
null表示空,但不是代表字符串,not null 也一樣



唯一性約束:
constraint host_port unique(host,port) 
#constraint host_port這個只是用來設置唯一約束的名字的,也可以不設置默認就有了
 

一個表中可以:

單列做主鍵
多列做主鍵(復合主鍵)

但一個表內只能有一個主鍵primary key


定義單個主鍵:
  1. 當沒有聲明主鍵時,第一個not null+unique默認是主鍵
  2. 某一個字段後加primary key
  3. 單獨定義 constraint pk_name primary key(id); #創建主鍵並為其命名pk_name

定義多個主鍵:

  1. 單獨定義 primary key(ip, port)

自增約束:

auto_incerment

偏移量:auto_increment_offset默認為1

    1. 設置自增的時候以10開頭
      1. create table dep1(
        id int primary key auto_increment,
        )auto_increment = 10;
    2. a

uto_increment_increment:

    自增步長,默認為1
    1. create
      table dep3( id int primary key auto_increment, name char(10) ); # 會話:通過客戶端連到服務端(一次鏈接稱為一次會話) set session auto_increment_increment = 2; #會話級,只對當前會話有效 set global auto_increment_increment=2; #全局,對所有的會話都有效 insert into dep3(name) values(IT),(HR),(SALE),(Boss);
  1. show variables like ‘%auto_in%‘;#查看變量。只要包含auto_in就都查出來了

外鍵約束:

技術分享圖片

兩表之間有關系,

先建張部門表(被關聯表)主表
create table dep(
id int not null unique,
name varchar(50),
comment varchar(100)
);
再建張員工表(關聯表)子表
create table emp_info(
id int primary key auto_increment,
name varchar(20),
dep_id int,
constraint FK_depid_id foreign key(dep_id) references dep(id) #references :關聯
on delete cascade  #關聯的表刪了,被關聯的表也刪了
on update cascade  #關聯的表修改了,被關聯的表也修改了
);

約束條件