多表查詢連接
准備倆張員工信息表,我們要查詢員工信息及員工所在部門.那么就需要倆張表進
行連接查詢,多表查詢.
外鏈接 語法
select 字段列表
from 表1 inner/left/right join 表2 on 表1.字段 = 表2.字段;
第一種情況交叉連接: 不適用任何匹配條件.生成笛卡爾積.
mysql> select * from employee,department; +----+----------+--------+------+--------+------+--------------+ | id | name | sex | age | dep_id | id | name | +----+----------+--------+------+--------+------+--------------+ | 1 | egon | male | 18 | 200 | 200 | 技術 | | 1 | egon | male | 18 | 200 | 201 | 人力資源 | | 1 | egon | male | 18 | 200 | 202 | 銷售 | | 1 | egon | male | 18 | 200 | 203 | 運營 | | 2 | alex | female | 48 | 201 | 200 | 技術 | | 2 | alex | female | 48 | 201 | 201 | 人力資源 | | 2 | alex | female | 48 | 201 | 202 | 銷售 | | 2 | alex | female | 48 | 201 | 203 | 運營 | | 3 | wupeiqi | male | 38 | 201 | 200 | 技術 | | 3 | wupeiqi | male | 38 | 201 | 201 | 人力資源 | | 3 | wupeiqi | male | 38 | 201 | 202 | 銷售 | | 3 | wupeiqi | male | 38 | 201 | 203 | 運營 | | 4 | yuanhao | female | 28 | 202 | 200 | 技術 | | 4 | yuanhao | female | 28 | 202 | 201 | 人力資源 | | 4 | yuanhao | female | 28 | 202 | 202 | 銷售 | | 4 | yuanhao | female | 28 | 202 | 203 | 運營 | | 5 | nvshen | male | 18 | 200 | 200 | 技術 | | 5 | nvshen | male | 18 | 200 | 201 | 人力資源 | | 5 | nvshen | male | 18 | 200 | 202 | 銷售 | | 5 | nvshen | male | 18 | 200 | 203 | 運營 | | 6 | xiaomage | female | 18 | 204 | 200 | 技術 | | 6 | xiaomage | female | 18 | 204 | 201 | 人力資源 | | 6 | xiaomage | female | 18 | 204 | 202 | 銷售 | | 6 | xiaomage | female | 18 | 204 | 203 | 運營 |
內連接 : 只連接匹配的行
#找兩張表共有的部分,相當於利用條件從笛卡爾積結果中篩選出了匹配的結果 #department沒有204這個部門,因而employee表中關於204這條員工信息沒有匹配出來 mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department
on employee.dep_id=department.id; +----+---------+------+--------+--------------+ | id | name | age | sex | name | +----+---------+------+--------+--------------+ | 1 | egon | 18 | male | 技術 | | 2 | alex | 48 | female | 人力資源 | | 3 | wupeiqi | 38 | male | 人力資源 | | 4 | yuanhao | 28 | female | 銷售 | | 5 | nvshen | 18 | male | 技術 | +----+---------+------+--------+--------------+ rows in set (0.00 sec) #上述sql等同於 mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;
外鏈接之右連接: 優先顯示右表全記錄
#以右表為准,即找出所有部門信息,包括沒有員工的部門 #本質就是:在內連接的基礎上增加右邊有,左邊沒有的結果 mysql> select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id=department.id; +------+---------+--------------+ | id | name | depart_name | +------+---------+--------------+ | 1 | egon | 技術 | | 2 | alex | 人力資源 | | 3 | wupeiqi | 人力資源 | | 4 | yuanhao | 銷售 | | 5 | nvshen | 技術 | | NULL | NULL | 運營 | +------+---------+--------------+ rows in set (0.00 sec)
外鏈接之左連接: 優先顯示左表全記錄
#以左表為准,即找出所有員工信息,當然包括沒有部門的員工 #本質就是:在內連接的基礎上增加左邊有,右邊沒有的結果 mysql> select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id=department.id; +----+----------+--------------+ | id | name | depart_name | +----+----------+--------------+ | 1 | egon | 技術 | | 5 | nvshen | 技術 | | 2 | alex | 人力資源 | | 3 | wupeiqi | 人力資源 | | 4 | yuanhao | 銷售 | | 6 | xiaomage | NULL | +----+----------+--------------+ rows in set (0.00 sec)
全外連接:顯示左右倆個表全部記錄
#外連接:在內連接的基礎上增加左邊有右邊沒有的和右邊有左邊沒有的結果 #注意:mysql不支持全外連接 full JOIN #強調:mysql可以使用此種方式間接實現全外連接 語法:select * from employee left join department on employee.dep_id = department.id union all select * from employee right join department on employee.dep_id = department.id; mysql> select * from employee left join department on employee.dep_id = department.id union select * from employee right join department on employee.dep_id = department.id ; +------+----------+--------+------+--------+------+--------------+ | id | name | sex | age | dep_id | id | name | +------+----------+--------+------+--------+------+--------------+ | 1 | egon | male | 18 | 200 | 200 | 技術 | | 5 | nvshen | male | 18 | 200 | 200 | 技術 | | 2 | alex | female | 48 | 201 | 201 | 人力資源 | | 3 | wupeiqi | male | 38 | 201 | 201 | 人力資源 | | 4 | yuanhao | female | 28 | 202 | 202 | 銷售 | | 6 | xiaomage | female | 18 | 204 | NULL | NULL | | NULL | NULL | NULL | NULL | NULL | 203 | 運營 | +------+----------+--------+------+--------+------+--------------+ rows in set (0.01 sec) #注意 union與union all的區別:union會去掉相同的紀錄
符合條件連接查詢
以內連接的方式查詢employee和department表,並且employee表中的age
字段值必須大於25,即找出年齡大於25歲的員工以及員工所在的部門.
select employee.name,department.name from employee inner join department on employee.dep_id = department.id where age > 25;
以內連接的方式查詢employee和department表,並且以age字段的升序方式顯示.
select employee.id,employee.name,employee.age,department.name from employee,department where employee.dep_id = department.id and age > 25 order by age asc;
子查詢
子查詢是將一個查詢語句嵌套在另一個查詢語句中.
內層查詢語句的查詢結果,可以為外層查詢語句提供查詢條件.
子查詢中可以包含:in, not in , any , all , exists 和 not exist等關鍵字
還可以包含比較運算符: = , != , > ,< 等
例 帶in 關鍵字的查詢
#查詢平均年齡在25歲以上的部門名 select id,name from department where id in (select dep_id from employee group by dep_id having avg(age) > 25); # 查看技術部員工姓名 select name from employee where dep_id in (select id from department where name='技術'); #查看不足1人的部門名 select name from department where id not in (select dep_id from employee group by dep_id);
帶比較運算的子查詢
#比較運算符:=、!=、>、>=、<、<=、<> #查詢大於所有人平均年齡的員工名與年齡 mysql> select name,age from employee where age > (select avg(age) from employee); +---------+------+ | name | age | +---------+------+ | alex | 48 | | wupeiqi | 38 | +---------+------+ #查詢大於部門內平均年齡的員工名、年齡 思路: (1)先對員工表(employee)中的人員分組(group by),查詢出dep_id以及平均年齡。 (2)將查出的結果作為臨時表,再對根據臨時表的dep_id和employee的dep_id作為篩選條件將employee表和臨時表進行內連接。 (3)最后再將employee員工的年齡是大於平均年齡的員工名字和年齡篩選。 mysql> select t1.name,t1.age from employee as t1 inner join (select dep_id,avg(age) as avg_age from employee group by dep_id) as t2 on t1.dep_id = t2.dep_id where t1.age > t2.avg_age; +------+------+ | name | age | +------+------+ | alex | 48 |
帶exists關鍵字的子查詢
#EXISTS關字鍵字表示存在。在使用EXISTS關鍵字時,內層查詢語句不返回查詢的記錄。而是返回一個真假值。True或False #當返回True時,外層查詢語句將進行查詢;當返回值為False時,外層查詢語句不進行查詢 #department表中存在dept_id=203,Ture mysql> select * from employee where exists (select id from department where id=200); +----+----------+--------+------+--------+ | id | name | sex | age | dep_id | +----+----------+--------+------+--------+ | 1 | egon | male | 18 | 200 | | 2 | alex | female | 48 | 201 | | 3 | wupeiqi | male | 38 | 201 | | 4 | yuanhao | female | 28 | 202 | | 5 | nvshen | male | 18 | 200 | | 6 | xiaomage | female | 18 | 204 | +----+----------+--------+------+--------+ #department表中存在dept_id=205,False mysql> select * from employee where exists (select id from department where id=204); Empty set (0.00 sec)
索引
索引介紹: 數據庫中專門用於幫助用戶快速查找數據的一種數據結構.類似
於字典中的目錄,查找字典內容時可以根據目錄查到數據的存放位置,然后
直接獲取.
索引作用 約束和加速查找
常見的索引:
普通索引; 唯一索引; 主鍵索引;
聯合索引(多列) : 聯合主鍵索引 聯合唯一索引 聯合普通索引
有無索引的區別以及建立索引的目的
無索引: 從前往后逐條查詢
有索引: 創建索引的本質,就是創建額外的文件(某種格式存儲,查詢的時
候,先去額外的文件找,定好位置,再去原始表中直接查詢.)數據過多,對硬
盤也有損耗.
建立索引目的 :
額外的文件保存特殊的數據結構
查詢快, 但是插入更新刪除依然慢
創建索引后,必須命中索引才能有效
hash索引和BTree索引 (1)hash類型的索引:查詢單條快,范圍查詢慢 (2)btree類型的索引:b+樹,層數越多,數據量指數級增長(我們就用它,因為innodb默認支持它)
普通索引 作用:僅有一個加速查找
創建表+普通索引
create table userinfo( nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, index ix_name(name)
#index創建索引目錄 ix_name表示創建的索引名字 (name)表示為哪個字段創建索引 );
普通索引
create index 索引的名字 on 表名(列名)
單獨為某一表的某一字段創建普通索引
刪除索引
drop index 索引的名字 on 表名
查看索引
show index from 表名
唯一索引
功能 : 加速查找 唯一約束(可含null)
create table userinfo( id int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, unique index ix_name(name) );
唯一索引: create unique index 索引名 on 表名(列名)
刪除唯一索引 : drop index 索引名 on 表名;
主鍵索引
(主鍵查找類似於 not null + unique 不為空且唯一)
功能:加速查找 唯一約束(不含null)
創建表+主鍵索引
create table userinfo( id int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, unique index ix_name(name) ) or create table userinfo( id int not null auto_increment, name varchar(32) not null, email varchar(64) not null, primary key(nid), unique index ix_name(name) )
主鍵索引 alter table 表名 add primary key(列名);
刪除主鍵索引
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
組合索引
組合索引是將n個列組合成一個索引,進行查詢,並不是采用n個列的各個
單列索引,進行查找,而是統一采用最左前綴規則查找.查找時采用最左面的
索引與后面的索引倆倆結合查找,最左面的索引不同,組合索引的效率也會不同.
其應用場景為: 頻繁的同時使用n列來進行查詢,如 :
where name='alex' and email='alex@aa.com'.
create index 索引名 on 表名(列名1,列名2);
組合索引總和保存了col1和col2的數據,他不需要在2個索引表之間跳轉,所以速度會更快,組合索引
的搜索步驟如下

索引名詞(非正規SQL名稱)
#覆蓋索引:在索引文件中直接獲取數據 例如: select name from userinfo where name = 'alex50000'; #索引合並:把多個單列索引合並成使用 例如: select * from userinfo where name = 'alex13131' and id = 13131;
如下圖索引合並,需要反復在倆個索引表間進行跳轉,造成速度慢的原因之一,假設col1='ABC'的數
據有5行,滿足col2=123的數據有1000行,最壞的情況(那5行在col2的1000行最后面) 需要掃描完col2的
1000行才能找到需要的數據,並不能達到快速查找的目的.

正確使用索引的情況
數據庫表中添加索引后確實會讓查詢速度飛起,但是前提必須是正確的使
用索引來查詢,如果以錯誤的方式使用,則即使建立索引也會不奏效.
使用索引,必須:
創建索引-->命中索引-->正確使用索引
測試:
#1. 准備表 create table userinfo( id int, name varchar(20), gender char(6), email varchar(50) ); #2. 創建存儲過程,實現批量插入記錄 delimiter $$ #聲明存儲過程的結束符號為$$ create procedure auto_insert1() BEGIN declare i int default 1; while(i<3000000)do insert into userinfo values(i,concat('alex',i),'male',concat('egon',i,'@oldboy')); set i=i+1; end while; END$$ #$$結束 delimiter ; #重新聲明分號為結束符號 #3. 查看存儲過程 show create procedure auto_insert1\G #4. 調用存儲過程 call auto_insert1(); - like '%xx' select * from userinfo where name like '%al'; - 使用函數 select * from userinfo where reverse(name) = 'alex333'; - or select * from userinfo where id = 1 or email = 'alex122@oldbody'; 特別的:當or條件中有未建立索引的列才失效,以下會走索引 select * from userinfo where id = 1 or name = 'alex1222'; select * from userinfo where id = 1 or email = 'alex122@oldbody' and name = 'alex112' - 類型不一致 如果列是字符串類型,傳入條件是必須用引號引起來,不然... select * from userinfo where name = 999; - != select count(*) from userinfo where name != 'alex' 特別的:如果是主鍵,則還是會走索引 select count(*) from userinfo where id != 123 - > select * from userinfo where name > 'alex' 特別的:如果是主鍵或索引是整數類型,則還是會走索引 select * from userinfo where id > 123 select * from userinfo where num > 123 - order by select email from userinfo order by name desc; 當根據索引排序時候,選擇的映射如果不是索引,則不走索引 特別的:如果對主鍵排序,則還是走索引: select * from userinfo order by nid desc; - 組合索引最左前綴 如果組合索引為:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引
最左前綴
最左前綴匹配: create index ix_name_email on userinfo(name,email); select * from userinfo where name = 'alex'; select * from userinfo where name = 'alex' and email='alex@oldBody'; select * from userinfo where email='alex@oldBody'; 如果使用組合索引如上,name和email組合索引之后,查詢 (1)name和email ---使用索引 (2)name ---使用索引 (3)email ---不適用索引 對於同時搜索n個條件時,組合索引的性能好於多個單列索引 ******組合索引的性能>索引合並的性能*********
索引注意事項:
(1)避免使用select * (2)count(1)或count(列) 代替count(*) (3)創建表時盡量使用char代替varchar (4)表的字段順序固定長度的字段優先 (5)組合索引代替多個單列索引(經常使用多個條件查詢時) (6)盡量使用短索引 (create index ix_title on tb(title(16));特殊的數據類型 text類型) (7)使用連接(join)來代替子查詢 (8)連表時注意條件類型需一致 (9)索引散列(重復少)不適用於建索引,例如:性別不合適
執行計划
explain+查詢sql 用於顯示sql執行信息參數,根據參考信息可以進行sql優化
mysql> explain select * from userinfo; +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ | 1 | SIMPLE | userinfo | ALL | NULL | NULL | NULL | NULL | 2973016 | NULL | +----+-------------+----------+------+---------------+------+---------+------+---------+-------+ mysql> explain select * from (select id,name from userinfo where id <20) as A; +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 19 | NULL | | 2 | DERIVED | userinfo | range | PRIMARY | PRIMARY | 4 | NULL | 19 | Using where | +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+ rows in set (0.05 sec)
參數
select_type: 查詢類型 SIMPLE 簡單查詢 PRIMARY 最外層查詢 SUBQUERY 映射為子查詢 DERIVED 子查詢 UNION 聯合 UNION RESULT 使用聯合的結果 table: 正在訪問的表名 type: 查詢時的訪問方式,性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const ALL 全表掃描,對於數據表從頭到尾找一遍 select * from userinfo; 特別的:如果有limit限制,則找到之后就不在繼續向下掃描 select * from userinfo where email = 'alex112@oldboy' select * from userinfo where email = 'alex112@oldboy' limit 1; 雖然上述兩個語句都會進行全表掃描,第二句使用了limit,則找到一個后就不再繼續掃描。 INDEX : 全索引掃描,對索引從頭到尾找一遍 select nid from userinfo; RANGE: 對索引列進行范圍查找 select * from userinfo where name < 'alex'; PS: between and in > >= < <= 操作 注意:!= 和 > 符號 INDEX_MERGE: 合並索引,使用多個單列索引搜索 select * from userinfo where name = 'alex' or nid in (11,22,33); REF: 根據索引查找一個或多個值 select * from userinfo where name = 'alex112'; EQ_REF: 連接時使用primary key 或 unique類型 select userinfo2.id,userinfo.name from userinfo2 left join tuserinfo on userinfo2.id = userinfo.id; CONST:常量 表最多有一個匹配行,因為僅有一行,在這行的列值可被優化器剩余部分認為是常數,const表很快,因為它們只讀取一次。 select id from userinfo where id = 2 ; SYSTEM:系統 表僅有一行(=系統表)。這是const聯接類型的一個特例。 select * from (select id from userinfo where id = 1) as A; possible_keys:可能使用的索引 key:真實使用的 key_len: MySQL中使用索引字節長度 rows: mysql估計為了找到所需的行而要讀取的行數 ------ 只是預估值 extra: 該列包含MySQL解決查詢的詳細信息 “Using index” 此值表示mysql將使用覆蓋索引,以避免訪問表。不要把覆蓋索引和index訪問類型弄混了。 “Using where” 這意味着mysql服務器將在存儲引擎檢索行后再進行過濾,許多where條件里涉及索引中的列,當(並且如果)它讀取索引時,就能被存儲引擎檢驗,因此不是所有帶where子句的查詢都會顯示“Using where”。有時“Using where”的出現就是一個暗示:查詢可受益於不同的索引。 “Using temporary” 這意味着mysql在對查詢結果排序時會使用一個臨時表。 “Using filesort” 這意味着mysql會對結果使用一個外部索引排序,而不是按索引次序從表里讀取行。mysql有兩種文件排序算法,這兩種排序方式都可以在內存或者磁盤上完成,explain不會告訴你mysql將使用哪一種文件排序,也不會告訴你排序會在內存里還是磁盤上完成。 “Range checked for each record(index map: N)” 這個意味着沒有好用的索引,新的索引將在聯接的每一行上重新估算,N是顯示在possible_keys列中索引的位圖,並且是冗余的
慢日志記錄
開啟慢查詢日志,可以讓mysql記錄下查詢超過指定時間的語句,通過定位分
析性能的瓶頸,才能更好的優化數據庫系統性能.
(1) 進入MySql 查詢是否開了慢查詢 show variables like 'slow_query%'; 參數解釋: slow_query_log 慢查詢開啟狀態 OFF 未開啟 ON 為開啟 slow_query_log_file 慢查詢日志存放的位置(這個目錄需要MySQL的運行帳號的可寫權限,一般設置為MySQL的數據存放目錄) (2)查看慢查詢超時時間 show variables like 'long%'; ong_query_time 查詢超過多少秒才記錄 默認10秒 (3)開啟慢日志(1)(是否開啟慢查詢日志,1表示開啟,0表示關閉。) set global slow_query_log=1; (4)再次查看 show variables like '%slow_query_log%'; (5)開啟慢日志(2):(推薦) 在my.cnf 文件中 找到[mysqld]下面添加: slow_query_log =1 slow_query_log_file=C:\mysql-5.6.40-winx64\data\localhost-slow.log long_query_time = 1 參數說明: slow_query_log 慢查詢開啟狀態 1 為開啟 slow_query_log_file 慢查詢日志存放的位置 long_query_time 查詢超過多少秒才記錄 默認10秒 修改為1秒
分頁性能相關方案
第1頁: select * from userinfo limit 0,10; 第2頁: select * from userinfo limit 10,10; 第3頁: select * from userinfo limit 20,10; 第4頁: select * from userinfo limit 30,10; ...... 第2000010頁 select * from userinfo limit 2000000,10; PS:會發現,越往后查詢,需要的時間約長,是因為越往后查,全文掃描查詢,會去數據表中掃描查詢。
最有的解決方案
(1)只有上一頁和下一頁 做一個記錄:記錄當前頁的最大id或最小id 下一頁: select * from userinfo where id>max_id limit 10; 上一頁: select * from userinfo where id<min_id order by id desc limit 10; (2) 中間有頁碼的情況 select * from userinfo where id in( select id from (select * from userinfo where id > pre_max_id limit (cur_max_id-pre_max_id)*10) as A order by A.id desc limit 10 );
分頁性能相關方案
取當前表中的前十條記錄,每十條取一次,取若干次..
第1頁: select * from userinfo limit 0,10; 第2頁: select * from userinfo limit 10,10; 第3頁: select * from userinfo limit 20,10; 第4頁: select * from userinfo limit 30,10; ...... 第2000010頁 select * from userinfo limit 2000000,10; PS:會發現,越往后查詢,需要的時間約長,是因為越往后查,全文掃描查詢,會去數據表中掃描查詢。
解決辦法:
(1)只有上一頁和下一頁 做一個記錄:記錄當前頁的最大id或最小id 下一頁: select * from userinfo where id>max_id limit 10; 上一頁: select * from userinfo where id<min_id order by id desc limit 10; (2) 中間有頁碼的情況 select * from userinfo where id in( select id from (select * from userinfo where id > pre_max_id limit (cur_max_id-pre_max_id)*10) as A order by A.id desc limit 10 );
create unique index 索引名 on 表名(列名)
