一丶表與表之間的關系
背景:
由於如果只使用一張表存儲所有的數據,就會操作數據冗余,也會操作數據庫查詢效率低下等問題,所以會把一張表分成多個表. 但是表與表之間的關系就需要被,否則在創建數據庫表時,思維混亂,導致項目崩潰.
表與表之間存在三種關系:
1.一對一
2.一對多
3.多對多
如何找出表與表之間關系:
分析步驟:
#1、先站在左表的角度去找
是否左表的多條記錄可以對應右表的一條記錄,如果是,則證明左表的一個字段foreign key 右表一個字段(通常是id)
#2、再站在右表的角度去找
是否右表的多條記錄可以對應左表的一條記錄,如果是,則證明右表的一個字段foreign key 左表一個字段(通常是id)
#3、總結:
#多對一:
如果只有步驟1成立,則是左表多對一右表
如果只有步驟2成立,則是右表多對一左表
#多對多
如果步驟1和2同時成立,則證明這兩張表時一個雙向的多對一,即多對多,需要定義一個這兩張表的關系表來專門存放二者的關系
#一對一:
如果1和2都不成立,而是左表的一條記錄唯一對應右表的一條記錄,反之亦然。這種情況很簡單,就是在左表foreign key右表的基礎上,將左表的外鍵字段設置成unique即可
一對一:
含義:
1.將一對一的情況,當作是一對多情況處理,在任意一張表添加一個外鍵,並且這個外鍵要唯一,指向另外一張表主鍵.
2.直接將兩張表合並成一張表將兩張表的主鍵建立起連接,
3.讓兩張表里面主鍵相等
案例:
學生和客戶,班級和班長, 公民和身份號碼,國家和國旗都是一對一的關系
關聯方式:foreign key+unique
# 1. 創建表
create table customer0(
id int primary key auto_increment,
name varchar(20) not null,
qq varchar(10) not null,
phone char(16) not null
);
create table student0(
id int primary key auto_increment,
class_name varchar(20) not null,
customer_id int unique, #該字段一定要是唯一的
foreign key(customer_id) references customer0(id) #外鍵的字段一定要保證unique
on delete cascade
on update cascade
);
# 查看student表的詳細信息
#增加客戶
mysql> insert into customer0(name,qq,phone) values
('韓蕾','31811231',13811341220),
('楊瀾','123123123',15213146809),
('翁惠天','283818181',1867141331),
('楊宗河','283818181',1851143312),
('袁承明','888818181',1861243314),
('袁清','112312312',18811431230);
mysql> #增加學生
mysql> insert into student0(class_name,customer_id) values
('脫產1班',3),
('周末1期',4),
('周末1期',5);
一對多***:
含義:
1.A表中的某條數,可以被B表關聯N條
2.在多的一方添加一個外鍵,指向一的一方的主鍵
案例:一個出版社可以出版多本書
關聯方式:foreign key
# 1 . 創建出版社表
create table press(
id int primary key auto_increment,
name varchar(20)
);
# 2. 創建圖書表
create table books1(
bid int primary key auto_increment,
name char(10),
press_id int not null,
foreign key(press_id) references press(id)
on delete cascade on update cascade
);
# 3. 查看books表詳細結構
mysql> show create table books;
`name` char(10) DEFAULT NULL,
`press_id` int(11) NOT NULL,
PRIMARY KEY (`bid`),
KEY `press_id` (`press_id`),
CONSTRAINT `books_ibfk_1` FOREIGN KEY (`press_id`) REFERENCES `press` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 |
# 4. 增加數據
# press表
mysql> insert into press(name) values('北京工業書出版社'),('人民出版社');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0
# books表
mysql> insert into books(name,press_id) values('柴嘉欣',1),('精益求精',2);
Query OK, 2 rows affected (0.11 sec)
Records: 2 Duplicates: 0 Warnings: 0
多對多***:
含義:
1.引入第三張的概念,
2. 建立一張中間表,將多對多的關系,拆分成一對多的關系,中間表至少要有兩個外鍵,分別指向原來的那兩張表
關聯方式:
foreign key + 一張新的表
# 1. 創建圖書表
create table books1(
bid int primary key auto_increment,
name char(10)
);
# 2. 創建作者表
create table author(
aid int primary key auto_increment,
name varchar(20)
);
# 3. 第三張表
create table au_bo(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
# 給外鍵起名 ,fk_book ,
constraint fk_book foreign key(book_id) references books1(bid)
on update cascade
on delete cascade,
# 給外鍵起名 ,fk_auto ,
constraint fk_auto foreign key(author_id) references author(aid)
on update cascade
on delete cascade,
primary key(author_id,book_id)
);
# 4. 查看au_bo表結構
mysql> show create table au_bo;
| au_bo | CREATE TABLE `au_bo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author_id` int(11) NOT NULL,
`book_id` int(11) NOT NULL,
PRIMARY KEY (`author_id`,`book_id`),
UNIQUE KEY `id` (`id`),
KEY `fk_book` (`book_id`),
CONSTRAINT `fk_auto` FOREIGN KEY (`author_id`) REFERENCES `author` (`aid`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_book` FOREIGN KEY (`book_id`) REFERENCES `books1` (`bid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
# 5. 增加數據
mysql> insert into au_bo(author_id,book_id) values(1,1),(1,2),(2,1),(2,2),(3,2),(3,4);
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 3 | 2 |
| 7 | 3 | 4 |
+----+-----------+---------+
二丶增刪改查操作
表操作
1.創建表 create table 表名
2.刪除表 drop table 表名
3.查看表結構 desc 表名 / show create table 表名
4.修改表如下👇:
### 修改表
# 1. 修改表名
alter table 舊表名 rename 新表名;
# 2. 添加新字段 (新字段默認添加表的最后)
alter table 表名 add 新字段 類型(寬度) 約束;
# 3. 在已有 id 字段前,添加新的字段
alter table 表名 add 新字段 類型(寬度) 約束 first id;
# 4. 在已有 id 字段后,添加新的字段
alter table 表名 add 新字段 類型(寬度) 約束 after id;
# 5. 刪除 字段名
alter table 表名 drop 字段名;
# 6. 更改字段名 或約束 使用 change
alter table 表名 change 舊字段 新字段 類型(寬度) 約束
# change name username char(12) not null
# change name name char(12) not null
# change name name varchar(255) after id;
# 7. 只更新字段的類型或越是
alter table 表名 modify 存在的字段 新類型(寬度) 約束
# modify name char(12) unique ;
# modify name char(12) unique after id;
數據操作
增加:
# 添加一條信息
insert into 表名 value(id1,name1);
# 添加多條信息
insert into 表名 vlaues(id1,name1) ,(id2,name2),(id3,name3);
# 指定字段插入
insert into 表名(name) values('abc'),('123'),('張三');
# 添加 查詢信息 ,字段要一一對應
insert into 表1(name,gender) select username,sex from 表2;
刪除:
# 刪除表內所有數據 ,(如果主鍵存在自增,delete 不能清除主鍵自增信息)
delete from 表名;
# 指定條件刪除
delete from 表名 where 條件;
修改:
# 修改一個值
update 表名 set 字段=新值1 where 條件
# 修改多個值
update 表名 set 字段1=值1,字段2=值2 where 條件
查詢👇:
# 單表查詢 # 多表查詢
三丶單表查詢
單標查詢語法:
SELECT DISTINCT 字段1,字段2... FROM 表名 WHERE 條件 GROUP BY field HAVING 篩選 ORDER BY field LIMIT 限制條數
關鍵字執行的優先級
#3## 特別重要 👇 from :找到表:from where :拿着where指定的約束條件,去文件/表中取出一條條記錄 group by :將取出的一條條記錄進行分組group by,如果沒有group by,則整體作為一組 select :執行select distinct :去重 having :將分組的結果進行having過濾 order by : 將結果按條件排序:order by desc降序 acs升序 limit :限制結果的顯示條數
建表:
# 創建表 company.employee 員工id id int 姓名 emp_name varchar 性別 sex enum 年齡 age int 入職日期 hire_date date 崗位 post varchar 職位描述 post_comment varchar 薪水 salary double 辦公室 office int 部門編號 depart_id int #創建表 create table employee( id int not null unique auto_increment, emp_name varchar(20) not null, sex enum('male','female') not null default 'male', #大部分是男的 age int(3) unsigned not null default 28, hire_date date not null, post varchar(50), post_comment varchar(100), salary double(15,2), office int, #一個部門一個屋子 depart_id int ); #查看表結構 mysql> desc employee; +--------------+-----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | emp_name | varchar(20) | NO | | NULL | | | sex | enum('male','female') | NO | | male | | | age | int(3) unsigned | NO | | 28 | | | hire_date | date | NO | | NULL | | | post | varchar(50) | YES | | NULL | | | post_comment | varchar(100) | YES | | NULL | | | salary | double(15,2) | YES | | NULL | | | office | int(11) | YES | | NULL | | | depart_id | int(11) | YES | | NULL | | +--------------+-----------------------+------+-----+---------+----------------+ #插入記錄 #三個部門:教學,銷售,運營 insert into employee(emp_name,sex,age,hire_date,post,salary,office,depart_id) values ('egon','male',18,'20170301','老男孩駐沙河辦事處外交大使',7300.33,401,1), #以下是教學部 ('alex','male',78,'20150302','teacher',1000000.31,401,1), ('wupeiqi','male',81,'20130305','teacher',8300,401,1), ('yuanhao','male',73,'20140701','teacher',3500,401,1), ('liwenzhou','male',28,'20121101','teacher',2100,401,1), ('jingliyang','female',18,'20110211','teacher',9000,401,1), ('jinxin','male',18,'19000301','teacher',30000,401,1), ('成龍','male',48,'20101111','teacher',10000,401,1), ('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是銷售部門 ('丫丫','female',38,'20101101','sale',2000.35,402,2), ('丁丁','female',18,'20110312','sale',1000.37,402,2), ('星星','female',18,'20160513','sale',3000.29,402,2), ('格格','female',28,'20170127','sale',4000.33,402,2), ('張野','male',28,'20160311','operation',10000.13,403,3), #以下是運營部門 ('程咬金','male',18,'19970312','operation',20000,403,3), ('程咬銀','female',18,'20130311','operation',19000,403,3), ('程咬銅','male',18,'20150411','operation',18000,403,3), ('程咬鐵','female',18,'20140512','operation',17000,403,3) ; #ps:如果在windows系統中,插入中文字符,select的結果為空白,可以將所有字符編碼統一設置成gbk
簡單查詢:select
### 使用函數 select user(); # 獲取當前用戶 select database(); # 獲取當前數據庫 select now(); # 獲取當前時間 ### 簡單查詢 # 查詢全部字段 SELECT id,emp_name,sex,age,hire_date,post,post_comment,salary,office,depart_id FROM employee; # 查所有 SELECT * FROM employee; # 查詢指定字段 SELECT emp_name,salary FROM employee; ### 查詢去重 distinct # 查看有幾個部門 select distinct post from employee; ### 查詢通過四則運算 # 查看 每個人的年薪 select emp_name, salary*12 from emplpoyee; ### 更改別名 # as select emp_name, salary*12 AS Annual_salary from employee; # 字段后直接跟別名 select emp_name, salary*12 Annual_salary from employee; ### 定義顯示格式 # CONCAT()函數: 字段與分隔符號 以逗號間隔 select concat('姓名:',emp_name,'年薪:',salary*12) from employee; # CONCAT_WS()函數: 第一個參數必須是分隔符, select concat_ws(':' , emp_name, salary*12) from employee; # 結合CASE 語句: #語法: ( case when 條件1 then 顯示內容 when 條件2 then 顯示內容 else 顯示內容 end ) select ( case when emp_name='jingliyang' then emp_name when emp_name='alex' then concat(emp_name,'_BIGSB') else concat(emp_name,'SB') end ) as new_name from employee; #### 練習: #1 查出所有員工的名字,薪資,格式為 <名字:egon> <薪資:3000> # select concat('<名字:',emp_name,'>'),concat('<薪資:',salary,'>') from employee; #2 查出所有的崗位(去掉重復) # select distinct post from employee; #3 查出所有員工名字,以及他們的年薪,年薪的字段名為annual_year # select emp_name ,salary*12 from employee;
Where查詢:
### 常用的模式 # 比較運算符: > 大於, < 小於, >= 大於等於, <=小於等於 , != 不等於, <> 不等於 # between 80 and 100 : 在80 到 100 的范圍內, 包含 80 和 100 # in(80,90,100) : 值是80 或者 90 或者 100 # 模糊查詢 # like : % 表示任意多個字符, _表示一個字符 # 1. like 'a%' 以a開頭的. # 2. like '%a' 以a結尾的 # 3. like '_a' Xa 兩個字符 # 4. like 'a_' aX 兩個字符 # regexp :正則匹配 # 1. '^a' 以a開頭 # 2. '\d+' 純數字 # 3. 'a$' 以a結尾 # is 和 is not is null : 是空 is not null : 非空 # 邏輯運算符: and與 or或 not非
where案例
# 1. 條件查詢 select emp_name from employee where post='sale'; # 2. 多條件查詢 select emp_name , salary from employee where port='teacher' and salary>10000; # 3.關鍵字 between and select emp_name ,salary from employee where salary beetween 10000 and 20000; # 4.關鍵字 is null 判斷某個字段是不是空,不能用等號 select emp_name,post_comment from employee where post_comment is null; select emp_name,post_comment from employee where post_comment is not null; # 判斷是不是 select emp_name,post_comment from employee where post_comment='' ; # 5.關鍵字IN集合查詢 SELECT emp_name,salary FROM employee WHERE salary=3000 OR salary=3500 OR salary=4000 OR salary=9000 ; SELECT emp_name,salary FROM employee WHERE salary IN (3000,3500,4000,9000) ; SELECT emp_name,salary FROM employee WHERE salary NOT IN (3000,3500,4000,9000) ; # 6.關鍵字LIKE模糊查詢 通配符 '%' 多個字符 # 查詢eg開頭 select * from employee where emp_name like 'eg%'; 通配符 '_' 單個字符 # select * from employee where emp_name like 'al__'; # 7 . regexp 依據正則匹配數據 # 找到以jin開頭的數據 select emp_name ,salary*12 from employee where emp_name regexp '^jin' ### 練習 1. 查看崗位是teacher的員工姓名、年齡 # select emp_name , age from employee where post ='teacher'; 2. 查看崗位是teacher且年齡大於30歲的員工姓名、年齡 # select emp_name , age from employee where post ='teacher' and age>30; 3. 查看崗位是teacher且薪資在9000-10000范圍內的員工姓名、年齡、薪資 # select emp_name , age ,salary*12 from employee where post ='teacher' and salary between 9000 and 10000; 4. 查看崗位描述不為NULL的員工信息 # select * from employee where post_comment is not null; 5. 查看崗位是teacher且薪資是10000或9000或30000的員工姓名、年齡、薪資 # select emp_name , age ,salary from employee where post ='teacher' and salary in (9000,10000,30000); # select emp_name , age ,salary from employee where post ='teacher' and salary=9000 or salary=10000 or salary=30000; 6. 查看崗位是teacher且薪資不是10000或9000或30000的員工姓名、年齡、薪資 # select emp_name , age ,salary from employee where post ='teacher' and salary not in (9000,10000,30000); # select emp_name , age ,salary from employee where post ='teacher' and not (salary=9000 or salary=10000 or salary=30000); 7. 查看崗位是teacher且名字是jin開頭的員工姓名、年薪 # select emp_name ,salary*12 from employee where post='teacher' and emp_name like 'jin%'; # select emp_name ,salary*12 from employee where post='teacher' and emp_name regexp '^jin';
GROUP BY 分組查詢:
特點:
根據某個重復率比較高的字段進行的
一旦分組了就不能對具體的一條數據進行操作
group_concat():只用來做最重的顯示,不能作為中間的結果操作其他數據
分組具有去重的效果
### 單獨使用group by 關鍵字分組查詢 . 每次操作都是以組的形式操作這些數據 # 按照部門進行分組,獲得每個部門的名字 (有去重的效果) select post from employee group by post; ### group by 和 group_concat()函數一起使用 # group_concat()只是用來顯示內容 # 按照崗位分組,並查看組內所有成員 select post,group_concat(emp_name) from employee group by post; ### group by 和 聚合函數 一起使用 # 按照崗位分組,並查看每組有多少人 select post,count(id) as count for employee group by post; ##### 強調 1.如果我使用 unique 字段作為分組依據, 則每條記錄自成一組,這樣沒有意義 2. 通常多條記錄之間的某個字段值相同,該字段通常用來作為分組的依據
HAVING 組過濾:
特點:
對一個組進行條件篩選
優先級:
where > group by > having
1.where發生在分組group by之前,where可以有任意字段,where絕對不會和聚合函數一起使用.
2.having發生在分組group by之后,因而having可以使用分組的字段,單無法直接取到其他字段
## 驗證 1. mysql> select post from employee where count(salary) group by post; ERROR 1111 (HY000): Invalid use of group function ## 驗證 2. #錯誤,分組后無法直接取到salary字段 mysql> select post,group_concat(emp_name) from employee group by post having salary>1000; ERROR 1054 (42S22): Unknown column 'salary' in 'having clause' #可以使用聚合函數獲取未定義字段信息 mysql> select post,group_concat(emp_name) from employee group by post having avg(salary)>10000; +-----------+---------------------------------------------------------+ | post | group_concat(emp_name) | +-----------+---------------------------------------------------------+ | operation | 程咬鐵,程咬銅,程咬銀,程咬金,張野 | | teacher | 成龍,jinxin,jingliyang,liwenzhou,yuanhao,wupeiqi,alex | +-----------+---------------------------------------------------------+ ### 練習 1. 查詢各崗位內包含的員工個數小於2的崗位名、崗位內包含員工名字、個數 # select post, count(id),group_concat(emp_name) from employee group by post having count(id)<2; 3. 查詢各崗位平均薪資大於10000的崗位名、平均工資 # select post,avg(salary) from employee group by post having avg(salary)>10000; 4. 查詢各崗位平均薪資大於10000且小於20000的崗位名、平均工資 # select post,avg(salary) from employee group by post having avg(salary)>10000 and avg(salary)<20000; # select post,avg(salary) from employee group by post having avg(salary) between 10000 and 20000;
聚合函數:
count() :統計某個字段出現的次數
max() : 某個字段的最大值
min() : 某個字段的最小值
avg() : 某個字段的平均值
sum() : 某個字段進行求和
### 如果沒有進行分組, 那么這張表會作為一個整體成為一組 ### 應用實例 # 統計這張表有多少條記錄 select count(*) from employee; # 統計這個表id字段有效值有多少個.(有效值 指的是非空) select count(id) from employee; # 最高的工資 select max(salary) from employee; # 最低的工資 select min(salary) from employee; # 平均工資 select avg(salary) from employee; # 工資總和 select sum(salary) from employee; ### 練習 1. 查詢崗位名以及崗位包含的所有員工名字 # select post, group_concat(emp_name) from employee group by post; 2. 查詢崗位名以及各崗位內包含的員工個數 # select post, count(emp_name) from employee group by post; 3. 查詢公司內男員工和女員工的個數 # select count(emp_name),sex from employee group by sex; 4. 查詢崗位名以及各崗位的平均薪資 # select post, avg(salary) from employee group by post ; 5. 查詢崗位名以及各崗位的最高薪資 # select post, max(salary) from employee group by post ; 6. 查詢崗位名以及各崗位的最低薪資 # select post, min(salary) from employee group by post ; 7. 查詢男員工與男員工的平均薪資,女員工與女員工的平均薪資 # select sex, max(salary) from employee group by sex ; # 求各部門薪資大於1w的人的個數 select post,count(id) from employee where salary >10000 group by post;
ORDER BY 排序查詢:
特點:
1.對單字段, 對多字段進行排序
2.默認升序 從小到大
3.desc 降序 從大到小, asc 升序 從小到大
### 按單列排序 # 升序排序工資 select * from employee order by salary; # asc 升序 select * from employee order by salary asc; # desc 降序 select * from employee order by salary desc; ### 按多列排序: # 先排age 升序 ,再排 薪資 升序 select * from employee order by age , salary ; # 先排age 降序 ,再排 薪資 升序 select * from employee order by age desc , salary ; ### 練習 1. 查詢所有員工信息,先按照age升序排序,如果age相同則按照hire_date降序排序 # select * from employee order by age , hire_date desc; 2. 查詢各崗位平均薪資大於10000的崗位名、平均工資,結果按平均薪資升序排列 # select post , avg(salary) from employee group by post having avg(salary)>10000 order by avg(salary); 3. 查詢各崗位平均薪資大於10000的崗位名、平均工資,結果按平均薪資降序排列 # select post , avg(salary) from employee group by post having avg(salary)>10000 order by avg(salary) desc;
LIMIT限制查詢:
特點:
1.limit(n,m) : n默認從0開始 , 從n+1開始, 取m條
2.與 limit n offset m : 用法一直
3.limit(n) : 取n條
4.和order by 搭配使用
應用:
1.分頁
2.限制取值
## 實例 # 降序排序工資,每次取 3 條 select * from employee order by salary desc limit(3); # 從第1條開始,即查出第一條,包含這一條並繼續查詢5條 select * from employee order by salary desc limit 0,5; # 從第6條開始,即查出第6條,包含這一條並繼續查詢5條 select * from employee order by salary desc limit 5,5; ### 分頁練習 分頁顯示,每頁5條 mysql> select * from employee limit 0,5; +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ | id | emp_name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ | 1 | egon | male | 18 | 2017-03-01 | 老男孩駐沙河辦事處外交大使 | NULL | 7300.33 | 401 | 1 | | 2 | alex | male | 78 | 2015-03-02 | teacher | NULL | 1000000.31 | 401 | 1 | | 3 | wupeiqi | male | 81 | 2013-03-05 | teacher | NULL | 8300.00 | 401 | 1 | | 4 | yuanhao | male | 73 | 2014-07-01 | teacher | NULL | 3500.00 | 401 | 1 | | 5 | liwenzhou | male | 28 | 2012-11-01 | teacher | NULL | 2100.00 | 401 | 1 | +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ mysql> select * from employee limit 5,5; +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ | id | emp_name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ | 6 | jingliyang | female | 18 | 2011-02-11 | teacher | NULL | 9000.00 | 401 | 1 | | 7 | jinxin | male | 18 | 1900-03-01 | teacher | NULL | 30000.00 | 401 | 1 | | 8 | 成龍 | male | 48 | 2010-11-11 | teacher | NULL | 10000.00 | 401 | 1 | | 9 | 歪歪 | female | 48 | 2015-03-11 | sale | NULL | 3000.13 | 402 | 2 | | 10 | 丫丫 | female | 38 | 2010-11-01 | sale | NULL | 2000.35 | 402 | 2 | +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ 5 rows in set (0.00 sec)
正則查詢:
特點:
mysql可以使用正則進行查詢
## 實例 # emp_name字段以al開頭的數據 select * from employee where emp_name regexp '^al'; # emp_name字段以on結尾的數據 select * from employee where emp_name regexp 'on$'; # emp_name字段以al開頭的數據 select * from employee where emp_name regexp '^al';