MySQL學習(4) 資料表的約束

2021-10-11 03:05:15 字數 2495 閱讀 2908

參考:

主鍵作用

用來唯一標識資料庫中的每一條記錄

特徵通常不用業務字段作為主鍵,單獨給每張表設計乙個 id 的字段,把 id 作為主鍵。

主鍵是給資料庫和程式使用的,不是給最終的客戶使用的。所以主鍵有沒有含義沒有關係,只要不重複,非空就行。

下表中使用id作為主鍵,一般不使用身份證號、學號等。

建立主鍵

-

- 建立表學生表 st5, 包含字段(

id, name, age)將 id 做為主鍵

create table st5 (

idint primary key,

name varchar(20)

, age int

)

alter table employee add primary key(id)
刪除主鍵
-

- 刪除 st5 表的主鍵

alter table st5 drop primary key;

-- 新增主鍵

alter table st5 add primary key(id)

;

設定主鍵自增

在每次插入新記錄時,資料庫自動生成主鍵欄位的值

-

- 指定起始值為 1000

create table st4 (

idint primary key auto_increment,

name varchar(20)

) auto_increment =

1000

;insert into st4 values (null,

'孔明');

select *

from st4;

-- 修改起始值

alter table st4 auto_increment =

2000

;

唯一約束

表中不能出現重複的資料

欄位名 字段型別 unique
非空約束
欄位名 字段型別 not null
預設值
欄位名 字段型別 default 預設值
注意

外來鍵

--1

) 建立從表 employee 並新增外來鍵約束 emp_depid_fk

-- 多方,從表

create table employee(

idint primary key auto_increment,

name varchar(20)

,age int

,dep_id int,-

- 外來鍵對應主表的主鍵

-- 建立外來鍵約束

constraint emp_depid_fk foreign key (dep_id) references department(id)

)--2

) 正常新增資料

insert into employee (name, age, dep_id) values (

'張三',20

,1);

insert into employee (name, age, dep_id) values (

'李四',21

,1);

insert into employee (name, age, dep_id) values (

'王五',20

,1);

insert into employee (name, age, dep_id) values (

'老王',20

,2);

insert into employee (name, age, dep_id) values (

'大王',22

,2);

insert into employee (name, age, dep_id) values (

'小王',18

,2);

select *

from employee;--

3) 部門錯誤的資料新增失敗

-- 插入不存在的部門

-- cannot add or update a child row: a foreign key constraint fails

insert into employee (name, age, dep_id) values (

'老張',18

,6);

alter table 從表 drop foreign key 外來鍵名稱;
外來鍵級

mysql學習4 資料表

資料表是資料庫最重要的組成部分之一,是其他物件的基礎。1.使用資料庫 use db name 2.建立資料表 create table if not exists table name column name data type,3.檢視資料表 show tables from db name sh...

MySQL約束 資料表操作

作用 保證資料的完整性 一致性。分類 表級約束 對多個資料列的約束列級約束 對乙個資料列的約束 區別 表級約束只能在列定義時宣告 列級約束可以在定義後宣告 具體 not null非空約束primary key主鍵約束 保證唯一性,自動為非空,只有乙個unique key唯一約束 保證唯一性,可以為空...

mysql學習記錄(四)資料表的約束

約束條件 說明primary key pk 主鍵foreign key fk 外來鍵not null nk 不為空unique uk 值是唯一的 auto increment 自動增長 default 預設值constraint pk name primary key 欄位一,欄位二.pk name...