MySQL 子查詢和分組查詢
概述
子查詢是SQL查詢中的重要一塊,是我們基于多表之間進(jìn)行數(shù)據(jù)聚合和判斷的一種手段,使得我們的處理復(fù)雜數(shù)據(jù)更加的便捷,這一節(jié)我們主要來(lái)了解一下子查詢。
先做一下數(shù)據(jù)準(zhǔn)備,這邊建立三張表:班級(jí)、學(xué)生、畢業(yè)成績(jī)表,用于后面的操作:
drop database if exists `Helenlyn_Class`; create database `Helenlyn_Class`; /*班級(jí)表*/ DROP TABLE IF EXISTS `classes`; CREATE TABLE `classes` ( `classid` int primary key AUTO_INCREMENT comment '班級(jí)id', `classname` varchar(30) DEFAULT NULL comment '班級(jí)名稱' ) ENGINE=InnoDB comment '班級(jí)表'; insert into `classes`(`classname`) values ('初三一班'),('初三二班'),('初三三班'); /*學(xué)生表:這邊假設(shè)學(xué)生id和姓名都具有唯一性*/ DROP TABLE IF EXISTS `students`; CREATE TABLE `students` ( `studentid` int primary key NOT NULL AUTO_INCREMENT comment '學(xué)生id', `studentname` varchar(20) DEFAULT NULL comment '學(xué)生姓名', `score` DECIMAL(10,2) DEFAULT NULL comment '畢業(yè)成績(jī)', `classid` int(4) DEFAULT NULL comment '所屬班級(jí)id,來(lái)源于classes表的classid' ) ENGINE=InnoDB comment '學(xué)生表'; insert into `students`(`studentname`,`score`,`classid`) values ('brand',97.5,1),('helen',96.5,1),('lyn',96,1),('sol',97,1),('weng',100,1),('diny',92.7,1), ('b1',81,2),('b2',82,2),('b3',83,2),('b4',84,2),('b5',85,2),('b6',86,2), ('c1',71,3),('c2',72.5,3),('c3',73,3),('c4',74,3),('c5',75,3),('c6',76,3); /*畢業(yè)考核分?jǐn)?shù)排名表*/ DROP TABLE IF EXISTS `scores`; CREATE TABLE `scores`( `scoregrad` varchar(3) primary key comment '等級(jí):S、A、B、C、D', `downset` int comment '分?jǐn)?shù)評(píng)級(jí)下限', `upset` int comment '分?jǐn)?shù)評(píng)級(jí)上限' ) comment '畢業(yè)考核分?jǐn)?shù)排名表'; INSERT INTO `scores` values ('S', 91, 100),('A', 81, 90),('B', 71, 80),('C', 61, 70),('D', 51,60);
子查詢
SQL支持創(chuàng)建子查詢( subquery) ,就是嵌套在其他查詢中的查詢 ,也就是說(shuō)在select語(yǔ)句中會(huì)出現(xiàn)其他的select語(yǔ)句,我們稱為子查詢或內(nèi)查詢。而外部的select語(yǔ)句,稱主查詢或外查詢。
子查詢分類
按照查詢的返回結(jié)果
1、單行單列(標(biāo)量子查詢):返回的是一個(gè)具體列的內(nèi)容,可以理解為一個(gè)單值數(shù)據(jù);
2、單行多列(行子查詢):返回一行數(shù)據(jù)中多個(gè)列的內(nèi)容;
3、多行單列(列子查詢):返回多行記錄之中同一列的內(nèi)容,相當(dāng)于給出了一個(gè)操作范圍;
4、多行多列(表子查詢):查詢返回的結(jié)果是一張臨時(shí)表;
按子查詢位置區(qū)分
select后的子查詢:僅僅支持標(biāo)量子查詢,即只能返回一個(gè)單值數(shù)據(jù)。
from型子查詢:把內(nèi)層的查詢結(jié)果當(dāng)成臨時(shí)表,供外層sql再次查詢,所以支持的是表子查詢。
where或having型子查詢:指把內(nèi)部查詢的結(jié)果作為外層查詢的比較條件,支持標(biāo)量子查詢(單列單行)、列子查詢(單列多行)、行子查詢(多列多行)。
一般會(huì)和下面這幾種方式配合使用:
1)、in子查詢:內(nèi)層查詢語(yǔ)句僅返回一個(gè)數(shù)據(jù)列,這個(gè)數(shù)據(jù)列的值將供外層查詢語(yǔ)句進(jìn)行比較。
2)、any子查詢:只要滿足內(nèi)層子查詢中的任意一個(gè)比較條件,就返回一個(gè)結(jié)果作為外層查詢條件。
3)、all子查詢:內(nèi)層子查詢返回的結(jié)果需同時(shí)滿足所有內(nèi)層查詢條件。
4)、比較運(yùn)算符子查詢:子查詢中可以使用的比較運(yùn)算符如 >、>=、<=、<、=、 <>
exists子查詢:把外層的查詢結(jié)果(支持多行多列),拿到內(nèi)層,看內(nèi)層是否成立,簡(jiǎn)單來(lái)說(shuō)后面的返回true,外層(也就是前面的語(yǔ)句)才會(huì)執(zhí)行,否則不執(zhí)行。
下面我們一個(gè)個(gè)來(lái)測(cè)試。
select后子查詢
位于select后面,僅僅支持標(biāo)量子查詢,即只能返回一個(gè)單值數(shù)據(jù)。比如上面的學(xué)生班級(jí)表,我們查詢每個(gè)班級(jí)的學(xué)生數(shù)量,可以這么寫(xiě):
mysql> select a.classid as 班級(jí)編號(hào),a.classname as 班級(jí)名稱, (select count(*) from students b where b.classid = a.classid) as 學(xué)生數(shù)量 from classes a; +----------+----------+----------+ | 班級(jí)編號(hào) | 班級(jí)名稱 | 學(xué)生數(shù)量 | +----------+----------+----------+ | 1 | 初三一班 | 6 | | 2 | 初三二班 | 6 | | 3 | 初三三班 | 6 | +----------+----------+----------+ 3 rows in set
查詢學(xué)生brand 所屬的班級(jí),可以這么寫(xiě):
mysql> select (select classname from classes a,students b where a.classid = b.classid and b.studentname='brand') as 班級(jí); +----------+ | 班級(jí) | +----------+ | 初三一班 | +----------+ 1 row in set
from后子查詢
把內(nèi)層的查詢結(jié)果當(dāng)成臨時(shí)表,提供外層sql再次查詢,支持的是表子查詢。但是必須對(duì)子查詢起別名,否則無(wú)法找到表。
查詢每個(gè)班級(jí)的平均成績(jī):
mysql> select a.classid,avg(a.score) from students a group by a.classid; +---------+--------------+ | classid | avg(a.score) | +---------+--------------+ | 1 | 96.616667 | | 2 | 83.500000 | | 3 | 73.583333 | +---------+--------------+ 3 rows in set
查詢畢業(yè)考核分?jǐn)?shù)排名表:S開(kāi)始從高到低排序。
mysql> select * from scores order by upset desc; +-----------+---------+-------+ | scoregrad | downset | upset | +-----------+---------+-------+ | S | 91 | 100 | | A | 81 | 90 | | B | 71 | 80 | | C | 61 | 70 | | D | 51 | 60 | +-----------+---------+-------+ 5 rows in set
如果綜合兩個(gè)查詢結(jié)果,想查出 各個(gè)班級(jí)的平均成績(jī)是位于什么段位,就可以用from后子查詢,代碼如下:
select a.classid as 班級(jí)id,a.avgscore 平均畢業(yè)分?jǐn)?shù),b.scoregrad 分?jǐn)?shù)評(píng)級(jí) from (select classid,avg(score) as avgscore from students group by classid) as a, scores b where a.avgscore between b.downset and b.upset; +--------+--------------+----------+ | 班級(jí)id | 平均畢業(yè)分?jǐn)?shù) | 分?jǐn)?shù)評(píng)級(jí) | +--------+--------------+----------+ | 1 | 96.616667 | S | | 2 | 83.500000 | A | | 3 | 73.583333 | B | +--------+--------------+----------+ 3 rows in set
對(duì)于子表查詢,必須提供別名,否則會(huì)提示:Every derived table must have its own alias,可以試試。
where和having型的子查詢
根據(jù)我們上面提到過(guò)的內(nèi)容,where或having后面,可以使用3種方式:標(biāo)量子查詢(單行單列行子查詢);列子查詢(單列多行子查詢)行子查詢(多行多列);
他有如下共同的特點(diǎn):
1、一般用括號(hào)將子查詢包起來(lái)。
2、子查詢一般放在條件的右側(cè)。
3、標(biāo)量子查詢,一般搭配著單行操作符使用,多行操作符 >、<、>=、<=、=、<>
4、列子查詢,一般搭配著多行操作符使用
5、配合 in、not in、all、any使用,in是指列表中的任意一個(gè),any是比較列表中任意一個(gè) score>any(60,70,80) 則 score>60即可;all 是比較列表中所有,score > (60,70,80),score需 >80。
單個(gè)標(biāo)量子查詢應(yīng)用
就是where或者h(yuǎn)aving后面只跟一個(gè)標(biāo)量查詢的,比如查詢出比diny(92.7分)成績(jī)好的同學(xué):
mysql> select * from students a where a.score >(select b.score from students b where b.studentname='diny'); +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 1 | brand | 97.5 | 1 | | 2 | helen | 96.5 | 1 | | 3 | lyn | 96 | 1 | | 4 | sol | 97 | 1 | | 5 | weng | 100 | 1 | +-----------+-------------+-------+---------+ 5 rows in set
多個(gè)標(biāo)量子查詢應(yīng)用
where或者h(yuǎn)aving后面只跟一個(gè)標(biāo)量查詢的,比如查詢出比diny(92.7分)成績(jī)差的同學(xué),并且班級(jí)跟diny不在同一班:
mysql> select * from students a where a.score <(select b.score from students b where b.studentname='diny') and a.classid <> (select b.classid from students b where b.studentname='diny') ; +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 7 | b1 | 81 | 2 | | 8 | b2 | 82 | 2 | | 9 | b3 | 83 | 2 | | 10 | b4 | 84 | 2 | | 11 | b5 | 85 | 2 | | 12 | b6 | 86 | 2 | | 13 | c1 | 71 | 3 | | 14 | c2 | 72.5 | 3 | | 15 | c3 | 73 | 3 | | 16 | c4 | 74 | 3 | | 17 | c5 | 75 | 3 | | 18 | c6 | 76 | 3 | +-----------+-------------+-------+---------+ 12 rows in set
子查詢+分組函數(shù)
分別取出三個(gè)班級(jí)的平均成績(jī),并篩選出低于全年級(jí)的平均成績(jī)的班級(jí)信息,使用having表達(dá)式
mysql> select a.classid,avg(a.score) as avgscore from students a group by a.classid having avgscore < (select avg(score) from students); +---------+-----------+ | classid | avgscore | +---------+-----------+ | 2 | 83.500000 | | 3 | 73.583333 | +---------+-----------+ 2 rows in set
列子查詢說(shuō)明
列的子查詢需要搭配多行操作符:in(not in)、any/some、all。使用distinct關(guān)鍵字進(jìn)行去重可以提高執(zhí)行效率。
列子查詢+in:所有非三班的同學(xué)
mysql> select * from students a where a.classid in (select distinct b.classid from classes b where b.classid <3); +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 1 | brand | 97.5 | 1 | | 2 | helen | 96.5 | 1 | | 3 | lyn | 96 | 1 | | 4 | sol | 97 | 1 | | 5 | weng | 100 | 1 | | 6 | diny | 92.7 | 1 | | 7 | b1 | 81 | 2 | | 8 | b2 | 82 | 2 | | 9 | b3 | 83 | 2 | | 10 | b4 | 84 | 2 | | 11 | b5 | 85 | 2 | | 12 | b6 | 86 | 2 | +-----------+-------------+-------+---------+ 12 rows in set
列子查詢+any:任意非三班的同學(xué)
mysql> select * from students a where a.classid = any (select distinct b.classid from classes b where b.classid <3); +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 1 | brand | 97.5 | 1 | | 2 | helen | 96.5 | 1 | | 3 | lyn | 96 | 1 | | 4 | sol | 97 | 1 | | 5 | weng | 100 | 1 | | 6 | diny | 92.7 | 1 | | 7 | b1 | 81 | 2 | | 8 | b2 | 82 | 2 | | 9 | b3 | 83 | 2 | | 10 | b4 | 84 | 2 | | 11 | b5 | 85 | 2 | | 12 | b6 | 86 | 2 | +-----------+-------------+-------+---------+ 12 rows in set
列子查詢+all:等同于 not in
mysql> select * from students a where a.classid <> all (select distinct b.classid from classes b where b.classid <3); +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 13 | c1 | 71 | 3 | | 14 | c2 | 72.5 | 3 | | 15 | c3 | 73 | 3 | | 16 | c4 | 74 | 3 | | 17 | c5 | 75 | 3 | | 18 | c6 | 76 | 3 | +-----------+-------------+-------+---------+ 6 rows in set
行子查詢說(shuō)明
查詢學(xué)生編號(hào)最小但是成績(jī)最好的同學(xué):
mysql> select * from students a where (a.studentid, a.score) in (select max(studentid),min(score) from students); +-----------+-------------+-------+---------+ | studentid | studentname | score | classid | +-----------+-------------+-------+---------+ | 19 | lala | 51 | 0 | +-----------+-------------+-------+---------+ 1 row in set
exists子查詢
也叫做相關(guān)子查詢,就是把外層的查詢結(jié)果(支持多行多列),拿到內(nèi)層,看內(nèi)層是否成立,簡(jiǎn)單來(lái)說(shuō)后面的返回true,外層(也就是前面的語(yǔ)句)才會(huì)執(zhí)行,否則不執(zhí)行。
1、exists查詢結(jié)果:1或0,1為true,0為false,exists查詢的結(jié)果用來(lái)判斷子查詢的結(jié)果集中是否有值。
2、exists子查詢,一般可以用in來(lái)替代,所以exists用的少。
3、和前面的那些查詢方式不同,先執(zhí)行主查詢,然后根據(jù)主查詢的結(jié)果,再用子查詢的結(jié)果來(lái)過(guò)濾。因?yàn)樽硬樵冎邪酥鞑樵冎杏玫降淖侄?,所以也叫相關(guān)子查詢。
示例,查詢所有學(xué)生的班級(jí)名稱
mysql> select classname from classes a where exists(select 1 from students b where b.classid = a.classid); +-----------+ | classname | +-----------+ | 初三一班 | | 初三二班 | | 初三三班 | +-----------+ 3 rows in set
使用 in 來(lái)替代(看著更簡(jiǎn)潔):
mysql> select classname from classes a where a.classid in(select classid from students); +-----------+ | classname | +-----------+ | 初三一班 | | 初三二班 | | 初三三班 | +-----------+ 3 rows in set
組合查詢
多數(shù)SQL查詢都只包含從一個(gè)或多個(gè)表中返回?cái)?shù)據(jù)的單條SELECT語(yǔ)句。 MySQL也允許執(zhí)行多個(gè)查詢(多條SELECT語(yǔ)句),并將結(jié)果作為單個(gè)
查詢結(jié)果集返回。這些組合查詢通常稱為并( union) 或復(fù)合查詢(compound query)。
單表多次返回
將不同查詢條件的結(jié)果組合在一起
select cname1,cname2 from tname where condition1 union select cname1,cname2 from tname where condition2
多表返回同結(jié)構(gòu)
將同數(shù)量結(jié)構(gòu)的字段組合
select t1_cname1,t1_cname2 from tname1 where condition union select t2_cname1,t_2cname2 from tname2 where condition
這邊不贅述,后面有專門(mén)的章節(jié)說(shuō)到這個(gè)
總結(jié)
可以按照查詢的返回類型和語(yǔ)句中子查詢的位置兩個(gè)方面來(lái)學(xué)習(xí)
注意使用 in、any、some、all的用法
無(wú)論是比較還是查詢還是count,字段中有null值總會(huì)引起誤解,建議建表時(shí)字段不為空,或者提供默認(rèn)值。
以上就是MySQL 子查詢和分組查詢的詳細(xì)內(nèi)容,更多關(guān)于MySQL 查詢的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
mysql實(shí)用技巧之比較兩個(gè)表是否有不同數(shù)據(jù)的方法分析
這篇文章主要介紹了mysql實(shí)用技巧之比較兩個(gè)表是否有不同數(shù)據(jù)的方法,結(jié)合實(shí)例形式分析了mysql數(shù)據(jù)表比較的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2019-12-12MySQL安裝starting?the?server失敗的2種解決辦法(推薦!)
MySQL是一個(gè)非常強(qiáng)大的關(guān)系型數(shù)據(jù)庫(kù),但有些初學(xué)者在安裝配置的時(shí)候,遇到種種的困難,下面這篇文章主要給大家介紹了關(guān)于MySQL安裝starting?the?server失敗的2種解決辦法,需要的朋友可以參考下2023-04-04Mysql主從數(shù)據(jù)庫(kù)(Master/Slave)同步配置與常見(jiàn)錯(cuò)誤
今天小編就為大家分享一篇關(guān)于Mysql主從數(shù)據(jù)庫(kù)(Master/Slave)同步配置與常見(jiàn)錯(cuò)誤,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-03-03Mysql中正則表達(dá)式Regexp常見(jiàn)用法
這篇文章主要介紹了Mysql中正則表達(dá)式Regexp常見(jiàn)用法,MySql REGEXP運(yùn)算符匹配字符串,mysql正則REGEXP學(xué)習(xí)練習(xí)筆記,需要的朋友可以參考下2020-02-02mysql數(shù)據(jù)庫(kù)鏈接失敗常見(jiàn)問(wèn)題及解決
這篇文章主要介紹了mysql數(shù)據(jù)庫(kù)鏈接失敗常見(jiàn)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11