一、表的約束條件
1、約束條件與資料型別的寬度一樣,都是可選引數
作用:用于保證資料的完整性和一致性
2、主鍵primary key是innodb存盤引擎組織資料的依據,innodb稱之為索引(索引是一種樹狀結構)組織表,一張表中必須有且只有一個主鍵
ps: 無 primary key欄位 ,無not null+unique
就會自動生成一個隱藏欄位,
所以建立表的時候要有id欄位,不為空且唯一的結構建立主鍵
作用:加速查詢,表結構,表資料檔案
# not null default create table t1(x int not null); insert into t1 values(); create table t2(x int not null default 111); insert into t2 values(); # unique # 單列唯一 create table t3(name varchar(10) unique); insert into t3 values("egon"); insert into t3 values("tom"); mysql> insert into t3 values("egon"); ERROR 1062 (23000): Duplicate entry 'egon' for key 'name' # 聯合唯一 create table server( id int, name varchar(10), ip varchar(15), port int, unique(ip,port), unique(name) ); insert into server values (1,"web1","10.10.0.11",8080); insert into server values (2,"web2","10.10.0.11",8081); mysql> insert into server values(4,"web4","10.10.0.11",8081); ERROR 1062 (23000): Duplicate entry '10.10.0.11-8081' for key 'ip' mysql> # not null 和unique的化學反應=>會被識別成表的主鍵 create table t4(id int,name varchar(10) not null unique); create table t5(id int,name varchar(10) unique); # 主鍵primary key # 特點 # 1、主鍵的約束效果是not null+unique # 2、innodb表有且只有一個主鍵,但是該主鍵可以是聯合主鍵 create table t6( id int primary key auto_increment, name varchar(5) ); insert into t6(name) values ("egon"), ("tom"), ("to1"), ("to2"); # 聯合主鍵(了解) create table t7( id int, name varchar(5), primary key(id,name) );
二、表之間的三種關系
多對一
關聯方式:foreign key
多對多
關聯方式:foreign key+一張新的表
一對一
關聯方式:foreign key+unique
ps: foreign key 限制表與表之間關系
# 引入 # 先創建被關聯表 create table dep( id int primary key auto_increment, name varchar(6), comment varchar(30) ); # 再創建關聯表 create table emp( id int primary key auto_increment, name varchar(10), gender varchar(5), dep_id int, foreign key(dep_id) references dep(id) on delete cascade on update cascade ); # 先往被關聯表插入資料 insert into dep(id,name) values (1,'技術部'), (2,'人力資源部'), (3,'銷售部'); # 先往關聯表插入資料 insert into emp(name,gender,dep_id) values ('egon',"male",1), ('alex1',"male",2), ('alex2',"male",2), ('alex3',"male",2), ('李坦克',"male",3), ('劉飛機',"male",3), ('張火箭',"male",3), ('林子彈',"male",3), ('加特林',"male",3) ; # 多對一 # 多對多 create table author( id int primary key auto_increment, name varchar(10) ); create table book( id int primary key auto_increment, name varchar(16) ); create table author2book( id int primary key auto_increment, author_id int, book_id int, foreign key(author_id) references author(id) on delete cascade on update cascade, foreign key(book_id) references book(id) on delete cascade on update cascade ); # 一對一 create table customer( id int primary key auto_increment, name varchar(16), phone char(11) ); create table student( id int primary key auto_increment, class varchar(10), course varchar(16), c_id int unique, foreign key(c_id) references customer(id) on delete cascade on update cascade );
三、
---44---
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3685.html
標籤:Python
上一篇:Django繼承AbstractUser和AbstractBaseUser時遷移問題
下一篇:Nginx快取
