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

2021-10-18 19:08:58 字數 1251 閱讀 7537

mysql建立約束的方法:1、建立表的時候,**為【constraint 索引名 foreign key(外來鍵列)】;2、建表完成之後,主鍵約束【alter table table_name add primary key (字段)】。

mysql建立約束的方法:

第一種:建立表的時候create table table_name(

列名1 資料型別 (int) primary key auto_increment,

列名2 資料型別 not null,

列名3 資料型別 unique,

列名4 資料型別 default '值',

constraint 索引名 foreign key(外來鍵列) references 主鍵表(主鍵列)

on delete cascade | on delete set null

第二種:建表完成之後1.主鍵約束

新增:alter table table_name add primary key (字段)

刪除:alter table table_name drop primary key

2.非空約束

新增:alter table table_name modify 列名 資料型別 not null

刪除:alter table table_name modify 列名 資料型別 null

3.唯一約束

新增:alter table table_name add unique 約束名(字段)

刪除:alter table table_name drop key 約束名

4.自動增長

新增:alter table table_name modify 列名 int auto_increment

刪除:alter table table_name modify 列名 int

5.外來鍵約束

新增:alter table table_name add constraint 約束名 foreign key(外來鍵列)

references 主鍵表(主鍵列)

刪除:第一步:刪除外來鍵

alter table table_name drop foreign key 約束名

第二步:刪除索引

alter table table_name drop index 索引名

[^1]:

約束名和索引名一樣

6.預設值

新增:alter table table_name alter 列名 set default '值'

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

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

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

create table tb name 1 建立表的主鍵約束 主鍵是唯一標識某字段的作用,當該字段為主鍵的時候,其值必須是唯一的,且不能為空。mysql create table student id int primary key,stu id int,course id int id為主鍵,所...

mysql建立外來鍵約束

mysql建立關聯表可以理解為是兩個表之間有個外來鍵關係,但這兩個表必須滿足三個條件 1.兩個表必須是innodb資料引擎 2.使用在外鍵關係的域必須為索引型 index 3.使用在外鍵關係的域必須與資料型別相似 例如 1 建立s user表 create table s user u id int...