(Structured Query Language)
結構查詢語句SQL
語句是一種what型語言【想要什麼,給你】,語法相對簡單易懂mysql
SQL
語言的劃分面試
(Data Definition Language)
-數據庫定義語言;用來定義數據庫對象、數據表和列;使用DDL建立、刪除、修改數據庫的表和結構(Data Manipulation Language)
-數據庫操做語言;操做數據庫的相關數據,好比增長、刪除、修改表中的數據(Data Control Language)
-數據控制語言;用它來定義訪問權限和安全等級(Data Query Language)
-數據查詢語言;數據查詢語言,用來查詢數據SQL
語句的執行順序sql
select distinct player_id , player_name , count(*) as num # 順序5 from player join team on player.team_id = team.team_id # 順序1 where height > 1.80 # 順序2 group by player.team_id # 順序3 having num >2 # 順序4 order by num desc # 順序6 limit 2; # 順序7
from
子句組裝數據(包括join
)where
子句進行條件篩選group by
分組having
篩選分組select
的字段order by
排序limit
篩選SQL
語句的執行流程數據庫
Mysql中的流程:SQL語句 → 緩存查詢 → 解析器 → 優化器 → 執行器緩存
查詢緩存:Server如何在查詢緩存總髮現了這條SQL語句,就會直接將結果返回給客戶端;若是沒有,就進入到解析器階段。須要說明的是,由於查詢緩存每每效率不高,因此在Mysql 8.0 以後就拋棄了這個功能。安全
解析器:在解析器中隊SQL語句進行語法分析、語義分析架構
優化器:在優化器中會肯定SQL語句的執行路徑,好比是根據全表檢索,仍是根據索引來檢驗等分佈式
執行器:在執行以前須要判斷改用戶是否具有權限,若是具有權限就執行SQL查詢並返回結果。在Mysql 8.0如下的版本,若是設置了查詢緩存,這時會將查詢結果進行緩存。函數
關於儲存引擎工具
InnoDB
儲存引擎
Mysql 5.5 版本後默認的儲存引擎,優勢是支持事務、行級鎖、外鍵約束、支持崩潰後的安全恢復
Myisam
儲存引擎
不支持事務和外鍵,支持全文索引(只對英文有效),特色是查詢速度快
Memory
儲存引擎
數據放在內存當中(相似memcache
)以便獲得更快的響應速度,可是崩掉的話數據會丟失
NDB
儲存引擎
主要用於Mysql Cluster 分佈式集羣
Archive
儲存引擎
有很好的壓縮機制,用於文件文檔,寫入時會進行壓縮
1. mysql -h localhost -u root -p # 以root用戶鏈接本地數據庫 2. show databases; # 查看Mysql服務中的全部數據庫 3. create database database_name; # 建立數據庫 4. use databases; # 更改操做的數據庫對象 5. \c # 取消執行當前未輸入mysql語句 6. show tables; # 查看該操做數據庫對象中全部的數據表名和視圖名 7. desc table_name/view_name; # 查看錶/視圖結構 8. truncate table_name; # 清空表數據【表結構不變】 9. delete from table_name; # 刪除表 10. show create table table_name; # 查看建表/視圖過程 11. show table status \G; # 查看數據庫中的全部表信息;\G 豎行顯示 12. show table status where name = table_name \G; # 指定表 13. rename table_name; # 改表名 14. drop table/view table_name/view_name; # 刪除表/視圖
insert
insert into table_name (column1,column2 ……) values (value1,value2 ……);
delete
delete from table_name where …… ; # where表示指定條件,不用where將針對表整表操做
update
update table_name set column1 = new_value , column2 = new_value …… where ……;
select
select cloumn1,cloumn2…… from table_name where …… group by …… having …… order by …… limit …… ; # where|group by|having|order by|limit 能夠沒有其中某些項,如有必須按照前後順序
select
select
是增刪改查的重點,也是難點,可否寫出高性能的sql
語句,select
是否熟練佔很大一部分
列是變量,變量就能夠進行各類運算,包括算術運算、邏輯運算 等
where
後面的語句是表達式,表達式的值爲真或假 eg:where 1
則恆爲真 查詢整張表,反之 where 0
恆位假 查詢結果位Empty
select 語句還能夠配合算術運算符、邏輯運算符、位運算符以及相關函數寫出更高性能的查詢語句
經常使用的select
用法以goods表爲例
數字篩選
select goods_id,goods_name,shop_price from goods where shop_price > 300;
字符篩選
select goods_id,goods_name,shop_price from goods where goods_name = 'kd876';
區間篩選
select goods_id,goods_name,shop_price from goods where shop_price between 300 and 3000;
多條件篩選
select goods_id,goods_name,shop_price from goods where shop_price between 300 and 3000 and goods_id > 10 ;
模糊條件篩選
select goods_id,goods_name,shop_price from goods where goods_name like '諾基亞%'; # 通配符% 表示任意多個字符 _ 表示任意單個字符
在字符串組裏篩選
select goods_id,goods_name,shop_price from goods where goods_id in (3,10); # goods_id in(3,10)等價於goods_id = 3 or goods_id = 10
藉助函數優化篩選
select goods_id,goods_name,shop_price from goods where left(goods_name,2)='kd'; # 函數left(a,n)表示在a字符串中從左到右取n個字符
全字符段篩選
select * from goods;
不重複篩選
select distinct goods_id,goods_name,shop_price from goods; # distinct 不重複的意思
排序篩選
select goods_id,goods_name,shop_price from goods where shop_price >300 order by shop_price desc; # asc升序(默認)/ desc 降序
補上後續練習所須要的表格代碼
create table goods ( goods_id mediumint(8) unsigned primary key auto_increment, goods_name varchar(120) not null default '', cat_id smallint(5) unsigned not null default '0', brand_id smallint(5) unsigned not null default '0', goods_sn char(15) not null default '', goods_number smallint(5) unsigned not null default '0', shop_price decimal(10,2) unsigned not null default '0.00', market_price decimal(10,2) unsigned not null default '0.00', click_count int(10) unsigned not null default '0' ) engine=InnoDB default charset=utf8; insert into `goods` values (1,'kd876',4,8,'ecs000000',1,1388.00,1665.60,9), (4,'諾基亞n85原裝充電器',8,1,'ecs000004',17,58.00,69.60,0), (3,'諾基亞原裝5800耳機',8,1,'ecs000002',24,68.00,81.60,3), (5,'索愛原裝m2卡讀卡器',11,7,'ecs000005',8,20.00,24.00,3), (6,'勝創kingmax內存卡',11,0,'ecs000006',15,42.00,50.40,0), (7,'諾基亞n85原裝立體聲耳機hs-82',8,1,'ecs000007',20,100.00,120.00,0), (8,'飛利浦9@9v',3,4,'ecs000008',1,399.00,478.79,10), (9,'諾基亞e66',3,1,'ecs000009',4,2298.00,2757.60,20), (10,'索愛c702c',3,7,'ecs000010',7,1328.00,1593.60,11), (11,'索愛c702c',3,7,'ecs000011',1,1300.00,0.00,0), (12,'摩托羅拉a810',3,2,'ecs000012',8,983.00,1179.60,13), (13,'諾基亞5320 xpressmusic',3,1,'ecs000013',8,1311.00,1573.20,13), (14,'諾基亞5800xm',4,1,'ecs000014',1,2625.00,3150.00,6), (15,'摩托羅拉a810',3,2,'ecs000015',3,788.00,945.60,8), (16,'恆基偉業g101',2,11,'ecs000016',0,823.33,988.00,3), (17,'夏新n7',3,5,'ecs000017',1,2300.00,2760.00,2), (18,'夏新t5',4,5,'ecs000018',1,2878.00,3453.60,0), (19,'三星sgh-f258',3,6,'ecs000019',12,858.00,1029.60,7), (20,'三星bc01',3,6,'ecs000020',12,280.00,336.00,14), (21,'金立 a30',3,10,'ecs000021',40,2000.00,2400.00,4), (22,'多普達touch hd',3,3,'ecs000022',1,5999.00,7198.80,16), (23,'諾基亞n96',5,1,'ecs000023',8,3700.00,4440.00,17), (24,'p806',3,9,'ecs000024',100,2000.00,2400.00,35), (25,'小靈通/固話50元充值卡',13,0,'ecs000025',2,48.00,57.59,0), (26,'小靈通/固話20元充值卡',13,0,'ecs000026',2,19.00,22.80,0), (27,'聯通100元充值卡',15,0,'ecs000027',2,95.00,100.00,0), (28,'聯通50元充值卡',15,0,'ecs000028',0,45.00,50.00,0), (29,'移動100元充值卡',14,0,'ecs000029',0,90.00,0.00,0), (30,'移動20元充值卡',14,0,'ecs000030',9,18.00,21.00,1), (31,'摩托羅拉e8 ',3,2,'ecs000031',1,1337.00,1604.39,5), (32,'諾基亞n85',3,1,'ecs000032',4,3010.00,3612.00,9); create table category ( cat_id smallint unsigned auto_increment primary key, cat_name varchar(90) not null default '', parent_id smallint unsigned )engine=InnoDB charset utf8; INSERT INTO `category` VALUES (1,'手機類型',0), (2,'CDMA手機',1), (3,'GSM手機',1), (4,'3G手機',1), (5,'雙模手機',1), (6,'手機配件',0), (7,'充電器',6), (8,'耳機',6), (9,'電池',6), (11,'讀卡器和內存卡',6), (12,'充值卡',0), (13,'小靈通/固話充值卡',12), (14,'移動手機充值卡',12), (15,'聯通手機充值卡',12); CREATE TABLE `result` ( `name` varchar(20) DEFAULT NULL, `subject` varchar(20) DEFAULT NULL, `score` tinyint(4) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into result values ('張三','數學',90), ('張三','語文',50), ('張三','地理',40), ('李四','語文',55), ('李四','政治',45), ('王五','政治',30); create table a ( id char(1), num int )engine=InnoDB charset utf8; insert into a values ('a',5),('b',10),('c',15),('d',10); create table b ( id char(1), num int )engine=InnoDB charset utf8; insert into b values ('b',5),('c',15),('d',20),('e',99); create table m( mid int, hid int, gid int, mres varchar(10), matime date )engine=InnoDB charset utf8; insert into m values (1,1,2,'2:0','2006-05-21'), (2,2,3,'1:2','2006-06-21'), (3,3,1,'2:5','2006-06-25'), (4,2,1,'3:2','2006-07-21'); create table t ( tid int, tname varchar(20) )engine=InnoDB charset utf8; insert into t values (1,'國安'), (2,'申花'), (3,'布爾聯隊'); create table mian ( num int) engine=InnoDB; insert into mian values (3), (12), (15), (25), (23), (29), (34), (37), (32); create table user ( uid int primary key auto_increment, name varchar(20) not null default '', age smallint unsigned not null default 0 ) engine=InnoDB charset utf8; create table boy ( hid char(1), bname varchar(20) )engine=InnoDB charset utf8; insert into boy (bname,hid) values ('屌絲','A'), ('楊過','B'), ('陳冠希','C'); create table girl ( hid char(1), gname varchar(20) )engine=InnoDB charset utf8; insert into girl(gname,hid) values ('小龍女','B'), ('張柏芝','C'), ('死宅女','D');
注:上述包含的表格有goods
、category
、result
、a
、b
、m
、t
、mian
、user
、boy
、girl
查詢出名字爲’諾基亞NXX’的手機
select * from goods where goods_id in(4,11);
查詢出名字不以’諾基亞’開頭的商品
select * from goods where goods_name not like '諾基亞%';
查詢出第4和第11行的全部信息
把goods
表中商品名爲’諾基亞xxxx’改成’HTCxxxx’
select goods_id, concat('HTC',substring(goods_name,4)) from goods where goods_name like '諾基亞%'; # 1. 函數concat(a,b) 將ab兩個字符串鏈接成一個字符串 # 2. 函數substring(string,position)從特定位置開始的字符串返回一個給定長度的子字符串
將mian
表中處於[20,29]之間的num
值改爲20,[30,39]之間的num
值改爲30,一句sql
完成。
update mian set num = (floor(num/10)*10) where num between 20 an 39; # 函數floor(x) 取不大於x的最大整數值
經常使用統計函數
max() # 獲取最大值 min() # 獲取最小值 avg() # 求取平均值 sum() # 求和 count() # 計算行數/條數 *特別注意count()返回的是一個總行數 distinct() # 求有多少種不一樣解
另外注意:當出現group by
分組種不能配對的狀況,該字段取查詢時候第一次出現的值
注:having
並不必定 與 where
共存(這種狀況能夠看作相似where 1
這種語句能夠忽略),但必定在where
以後;能夠存在只有having
而沒有where
的狀況
查詢goods
表中商品比市場價低出多少?
select goods_id ,goods_name,market_price - shop_price from goods ;
查詢goods
表中商品比市場價低出至少200元的商品
select goods_id ,goods_name,(market_price - shop_price) as discount from goods where market_price - shop_price ; # 注意爲何where後面不能用 discount
select goods_id,goods_name,(market_price-shop_price) as discount from goods having discount>200;
result
表,要求查詢出2門及2門以上不及格的平均成績 ※※※經典題目※※※
一種典型錯誤 ❌ 【錯誤點:對count和比較運算二者結合的理解錯誤】
msyql> select name , count(score<60) as gks , avg(score) as pjf from result group by name having gks >= 2; +--------+-----+---------+ | name | gks | pjf | +--------+-----+---------+ | 張三 | 3 | 60.0000 | | 李四 | 2 | 50.0000 | +--------+-----+---------+ 2 rows in set (0.00 sec) # 貌似是正確的,但只針對此種狀況
驗證:假如增長1行數據 values('趙六','語文',88),('趙六','數學',99),('趙六','物理',100)
再次執行上面的sql
語句,將會獲得以下結果
+--------+-----+---------+ | name | gks | pjf | +--------+-----+---------+ | 張三 | 3 | 60.0000 | | 李四 | 2 | 50.0000 | | 趙六 | 3 | 95.6667 | +--------+-----+---------+ 3 rows in set (0.00 sec) # 很明顯有語義上的錯誤!實際上count(score)和count(score<60)查詢出的結果是同樣的,函數count()返回的是總行數!
正確解題思路✅(逆向思惟)
1. select name ,avg(score),as pjf from result group by name; +--------+---------+ | name | pjf | +--------+---------+ | 張三 | 60.0000 | | 李四 | 50.0000 | | 王五 | 30.0000 | | 趙六 | 95.6667 | +--------+---------+ 4 rows in set (0.00 sec) # 1. 查詢出全部同窗的平均分,並分組
2. select name, score<60 from result; +--------+----------+ | name | score<60 | +--------+----------+ | 張三 | 0 | | 張三 | 1 | | 張三 | 1 | | 李四 | 1 | | 李四 | 1 | | 王五 | 1 | | 趙六 | 0 | | 趙六 | 0 | | 趙六 | 0 | +--------+----------+ 9 rows in set (0.00 sec) # 2. 查看每一個同窗的掛科狀況;這裏運用了邏輯運算,這個點也很重要!score<60 若真則返回0 若假則返回1
3. select name , sum(score<60) as gks from result group by name; +--------+------+ | name | gks | +--------+------+ | 張三 | 2 | | 李四 | 2 | | 王五 | 1 | | 趙六 | 0 | +--------+------+ 4 rows in set (0.00 sec) # 3. 計算每位同窗的總掛科數
4. select name ,sum(score<60) as gks ,avg(score) as pjf from result group by name having gks >=2; +--------+------+------------+ | name | gks | pjf | +--------+------+------------+ | 張三 | 2 | 60.0000 | | 李四 | 2 | 50.0000 | +--------+------+------------+ 2 rows in set (0.00 sec) # 4. 整合1.3步,獲得結果集,並篩選出gks大於等於2的同窗
按欄目由低到高排序,欄目內部按價格由高到低排序
select goods_id ,goods_name ,shop_price ,cat_id from goods order by cat_id desc,shop_price asc;
取出價格最高的前3名商品
select goods_id ,goods_name,shop_price from goods order by shop_price desc limit 0,3; # limit x,y 其中x表明起始位置也就是偏移量,y表明返回最大行數;x初始值爲0
取出商品市場價前10到25的商品信息
select goods_id ,goods_name,market_price from goods order by market_price limit 11,15;
mysql
子查詢是嵌套在另外一個查詢(如select
、insert
、update
或者delete
)中的查詢。這裏重點總結了嵌套在select
中的子查詢
cat_id
;最新的那件產品⇔goods_id
爲最大值時所對應的那一件產品# 1. 陷阱演示 ❌ # 思路:最新的商品 max(goods_id);每一個欄目 group by cat_id select max(goods_id) ,goods_name ,cat_id ,shop_price from goods group by cat_id ; # 報錯:ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated # column 'zion.goods.goods_name' which is not functionally dependent on columns in GROUP BY clause; # this is incompatible with sql_mode=only_full_group_by 大概意思是 語義缺陷,不兼容 #分析:」先查詢再排序「 group by cat_id 可是goods_name,shop_price應該取誰的呢?
# 2. 正確方法 ✅ # 思路:」先排序再查詢「 須要用到子查詢/鏈接查詢 # 」先排序「 select max(goods_id),cat_id from goods group by cat_id; +---------------+--------+ | max(goods_id) | cat_id | +---------------+--------+ | 16 | 2 | | 32 | 3 | | 18 | 4 | | 23 | 5 | | 7 | 8 | | 6 | 11 | | 26 | 13 | | 30 | 14 | | 28 | 15 | +---------------+--------+ 9 rows in set (0.00 sec) # 」再查詢「 select cat_id ,goods_id, goods_name, shop_price from goods where goods_id in (select max(goods_id) from goods group by cat_id); +--------+----------+----------------------------------------+------------+ | cat_id | goods_id | goods_name | shop_price | +--------+----------+----------------------------------------+------------+ | 11 | 6 | 勝創kingmax內存卡 | 42.00 | | 8 | 7 | 諾基亞n85原裝立體聲耳機hs-82 | 100.00 | | 2 | 16 | 恆基偉業g101 | 823.33 | | 4 | 18 | 夏新t5 | 2878.00 | | 5 | 23 | 諾基亞n96 | 3700.00 | | 13 | 26 | 小靈通/固話20元充值卡 | 19.00 | | 15 | 28 | 聯通50元充值卡 | 45.00 | | 14 | 30 | 移動20元充值卡 | 18.00 | | 3 | 32 | 諾基亞n85 | 3010.00 | +--------+----------+----------------------------------------+------------+ 9 rows in set (0.00 sec) # 分析:1.因而可知 select max(goods_id) ,goods_name ,shop_price from goods 除了goods_id符合題意,其它的在語義上就是存在缺陷的; # 這是一個有缺陷的語句。 # 2.列就是變量;把查詢這個變量(列)的sql語句做爲外層sql語句的比較條件,這麼作的目的是爲了咱們每次更新商品後,都能取得最新的那個商品。 # 這樣也不會出現 列與列不匹配錯亂的狀況
查詢出編號位19的商品的欄目名稱[欄目名稱放在category
表中]
select cat_id,cat_name from category where cat_id = ( select cat_id from goods where goods_id = 19 ); +--------+-----------+ | cat_id | cat_name | +--------+-----------+ | 3 | GSM手機 | +--------+-----------+ 1 row in set (0.00 sec)
==============未完待續……