MySQL添加約束


六大約束:

  NOT NULL (非空)
  DEFAULT (默認)
  UNIQUE (唯一) 【唯一約束可以為空值,但是不能重復】
  CHECK (檢查)【mysql不起作用】
  PRIMARY KEY (主鍵)【主鍵約束不能為空值,也不能重復】
  FOREIGN KEY (外鍵)

約束一般分為列級約束和表級約束。

列級約束不支持外鍵約束。

表級約束不支持非空和默認。

 

一、創建表時添加約束

模式:

  

create table 表名(
  a    類型    列級約束,
  b    類型    ,
  表級約束
)

 

舉例:

 

create table test(
  id int primary key  auto_increment,
  name varchar(50) not null,
  sex char default '',
  position varchar(10) unique,
  sex2 char(1) check(sex2 = 'male' or sex2 = 'female'),
  dept_id int references department(id)
)

 

二、修改表時添加約束

  

//列級約束
alter table test modify id int primary key;
alter table test modify name varchar(50) not null;
alter table test modify sex char default '';
alter table test modify position varchar(10) unique;

//表級約束
//中間起名的部分【】可省略,主鍵就算起名字也不會起作用,使用默認名字
alter table test addconstraint fk_test_department】 unique(position);
alter table test addconstraint fk_test_department】 primary key(id);
alter table test addconstraint fk_test_department】 foreign key(dept_id) references department(id); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM