mysql建立約束 MySQL 建立表及其約束

2021-10-17 12:24:28 字數 2107 閱讀 8795

create table [tb_name];

1、建立表的主鍵約束:主鍵是唯一標識某字段的作用,當該字段為主鍵的時候,其值必須是唯一的,且不能為空。

mysql>create table student(id int primary key,

stu_id int,

course_id int);id為主鍵,所有欄位都為整數

mysql>create table student (id int primary key,

stu_id int,

course_id int,

primary key(id,stu_id)

);  id和stu_id成為主鍵,兩者的組合唯一標識一條記錄

2、建立表的外來鍵約束(constraint:外來鍵別名;foreign key:外來鍵字段;references 父表):外來鍵是和另外乙個表關聯其來的作用,外來鍵必須是另一表的主鍵,外來鍵可以為空。

mysql>create table student (id int primary key,

stu_id int,

course_id int,

constraint c_fk foreign key(stu_id,course_id)

references example2(stu_id,course)

);表student的stu_id,course_id為外來鍵,外來鍵到example2表的stu_id,course_id主鍵。example2是student的父表。子表的外來鍵關聯的必須是父表的主鍵。而且,資料型別必須一致。

3、設定表的非空約束(not null):定義字段值不能為空

mysql>create table student(id int not null primary key,

name varchar(20) not null,

stu_id int,

constraint e_fk foreign key(stu_id)

references example1(stu_id)

); id為主鍵,not null定義id和stu_id為非空約束;constraint定義外來鍵別名,foreign key定義外來鍵字段,references定義父表;

4、設定表的唯一約束(unique):定義字段值唯一。

mysq>create table student(id int not null primary key,

name varchar(20) not null,

stu_id int unique,

*** char(6),

constraint e_fk foreign key(***)

references example2(***),

);id為主鍵且不能為空;name為字串型別且不能為空;sut_id為×××且只能唯一;***為字串且是外來鍵,example2為student父鍵。

5、設定表的屬性值自動增加:數字自動增長(auto_increment)

mysql>create table student(id int primary key auto_increment,

name varchar(20) not null,

stu_id unique auto_increment,

*** char(6) ,

constraint e_fk foreign key(***)

references example2(***),

);id為主鍵且自動增長不能為空,name為字串不能為空,stu_id是唯一鍵自動增長,***是外來鍵,example2是student的父表。

6、設定表屬性的預設值(如果插入一條新的記錄沒有為這個字段賦值,那麼資料庫系統會自動為這個字段插入預設值):default

mysql>create table student(id int primary key auto_increment,

name char(20) not null,

stu_id unique int auto_increment,

*** char(6) de****t 'man',

);id為自動增長整數型別,且是主鍵;name為字元型別,不能為空;stu_id是唯一鍵自動增長;***的預設值是man。

建立mysql約束 mysql如何建立約束?

方法 1 在建立表時,在字段後使用primary key和foreign key關鍵字建立主鍵和外來鍵約束 2 在建表後,通過 alter table 語句配合primary key not null unique等關鍵字來建立約束。mysql新增約束 第一種 建立表的時候create table ...

mysql創表 mysql建立表

1 說明 此檔案包含了blog資料庫中建立所有的表的mysql語句.2 3 在sql語句中注意 約束的概念 4 1.實體完整性約束 主鍵 唯一且非空 primary key 5 違約處理 no action 拒絕執行 6 7 2.參照完整性約束 外來鍵約束 foregin key reference...

mysql約束的建立 mysql如何建立約束

mysql建立約束的方法 1 建立表的時候,為 constraint 索引名 foreign key 外來鍵列 2 建表完成之後,主鍵約束 alter table table name add primary key 字段 mysql建立約束的方法 第一種 建立表的時候create table ta...