mysql之其他約束與多對一關係
一約束(需要先建立庫)
1,非空約束,資料不能為空
not null
create table student (id int,name char(10) not null);
2,預設值約束,可以指定欄位的預設值
default 預設值
create table user(id int,name char(10) not null,sex char(10) default 'woman');
3,唯一性約束,該欄位的值不能重複
一張表中可以存在多個唯一性約束
3.1,單列唯一約束
unique
create table t1(idcard char(18) unique);
3.2,多列聯合唯一約束(只限制括號裡面的值全部相同)
unique(存放兩個以上的欄位名)
create table t6(idcard char(18),phonenumber char(11),unique(idcard,phonenumber));
3.3,主鍵約束(表中一條非空且唯一的資訊)=unique not null
primary key
一個表中必須存在主鍵,如果沒有指定,系統會自上而下的搜尋一條非空且且唯一的資訊,如果定義的資訊不存在非空且唯一的,那麼系統會自動建一個7個bytes的隱藏欄位做主鍵
create table stu(stuid int primary key,name char(5)); create table t7(id int unique not null,name char(5));
3.4多列聯合主鍵(限制括號裡面的欄位全部相同)
primary key(多個欄位名)
create table t8(idcard char(18),phonenumber char(11),primary key(idcard,phonenumber));
3.5欄位型別屬於整數型的可以自動增長
auto_increment 通常搭配主鍵欄位使用,可以自動為你的資料分配
create table t9(id int primary key auto_increment,name char(3));
在插值的時候你可以跳過該欄位,也可以插入null
修改自動增長的起始位置:例:把起始位置改為5
alter table 表名 auto_increment=5
二,表與表之間的關係
2.1多對一
foreign key
1,在建立表時,需要先建立被關聯的表,才能建立關聯表
foreign key(關聯表的欄位名) references 被關聯表名(欄位名)
create table dep( id int prinmary key auto_increment, dep_name char(10), dep_comment char(60) ); create table emp( id int primary key auto_increment, name char(5), geder enum('male','female') not null default 'male', dep_id int, foreign key(dep_id) references dep(id) #外來鍵的主要語句 )
2,在插入記錄的時候,必須先插入被關聯表的,然後再插入關聯表的
幫助思考:想在學校新增一個學生,必須先建立幾個班級才能分配學生,要不然學生分配在哪裡?
3,更新與刪除都需要考慮到關聯與被關聯的關係
簡單的說外來鍵就是另一張表的主鍵
解決方法:外來鍵約束
1,先刪除關聯表,再刪除被關聯表,準備重建
mysql> drop table emp; Query OK, 0 rows affected (0.11 sec) mysql> drop table dep; Query OK, 0 rows affected (0.04 sec)
2,重建,新增功能,級聯操作(同步更新,與同步刪除)
語法:在建立外來鍵時,後面新增 on update cascade同步更新
on delete cascade 同步刪除
create table class(id int primary key auto_increment,name char(10)); create table student( id int primary key auto_increment, name char(10), c_id int, foreign key(c_id) references class(id) on update cascade on delete cascade ); insert into class value(null,"python"); insert into student value(null,"jack",1);
建立完之後,進行更改和刪除class,檢視效果
2.2多對多
兩張表實現多對多的關係建立,是建立第三張表,為了保證關係表中的資料不亂,該表中應該有關聯表的id與被關聯表的id,然後對這兩張表新增外來鍵約束,並且保證存放的都是有效資料,需要給這兩個資料新增關聯主鍵關係
create table student(id int,name char(5),sex enum('male','female')); create table student(id int,name char(5),sex enum('male','female')); create table t_s(t_id int, s_id int, foreign key(t_id) references teacher(id), #為t_id建立外來鍵 foreign key(s_id) references student(id), #為s_id建立外來鍵 primary key(t_id,s_id) #為兩個欄位名建立聯合主鍵 ) insert into student value(null,'jack'); insert into teacker value(null,'lily'); insert into t_s value(1,1);