聯合查詢
將多次查詢(多條select語句),在紀錄上進行拼接(字段不會增加)。
基本語法:多條select語句構成,每一條select語句獲取的字段數必須嚴格一致(但是字段類型無關)。
select 語句1 union[union 選項] select 語句2…….;
union選項:與select選項一樣有兩個,但默認的有區別
all:保留所有
distinct:去除重複(默認的)
select * from my_class union select * from my_class;
select * from my_class union all select * from my_class;
聯合查詢的意義:分爲兩種
1.查詢同一張表,但是需求不同:如查詢學生信息,男生身高升序,女生身高降序。
2.多表查詢:多張表的結構是完全一樣的,保存的數據(結構)也是一樣的。
注意:聯合查詢使用order by 時需要對查詢語句加括號
(select * from my_stu where sex='男' order by height asc limit 9999999)
union
(select * from my_stu where sex='女' order by height desc limit 9999999);
子查詢
子查詢:sub query,查詢是在某個查詢結果之上進行的(一條select語句內部包含了另外一條select語句)。
子查詢有兩種分類:按位置分類和按結果分類
按位置分類:子查詢(select語句)在外部查詢(select語句)中出現的位置。
form子查詢:子查詢跟在from之後
where子查詢:子查詢跟在where之後
exists子查詢:子查詢跟在exists之後
按結果分類:根據子查詢得到的數據進行分類(理論上講任何一個查詢得到的結果都可以理解爲二維表)。
標量子查詢:子查詢得到的結果是一行一列(出現的位置在where之後)。
列子查詢:子查詢得到的結果是多行一列(出現的位置在where之後)。
行子查詢:子查詢得到的結果是一行多列(出現的位置在where之後)。
表子查詢:子查詢得到的結果是多行多列(出現的位置在from之後)。
標量子查詢
需求:知道班級名字爲P1,想獲取該班的所有學生。
1.確定數據源:獲取所有學生
select * from my_stu where c_id =?;
2.獲取班級id:可以通過班級名字確定
select id from my_class where name = 'P1';
select * from my_stu where c_id =(select id from my_class where name = 'P1');
列子查詢
需求:查詢所有在讀班級的學生
1.確定數據源:學生
select * from my_stu where c_id in(?);
2.確定有效班級的id
select id from my_class;
select * from my_stu where c_id in(select id from my_class);
列子查詢返回的結果會比較多,需要使用in作爲條件匹配:其實在MySQL中還有幾個類型的條件:all,some,any
=any等價in
any等價some
=all等價全部
行子查詢
需求:要求查詢整個學生中,年齡最大且身高最高的學生
1.確定數據源:學生
select * from my_stu where age = ? and height= ?;
2.確定最大的年齡和身高
select max(age),max(height) from my_stu;
select * from my_stu where age = (select max(age)from my_stu)
and height= (select max(height) from my_stu);
但通過構造行元素的方式比較好:(行元素由多個字段構成)
select * from my_stu where (age,height)=
(select max(age),max(height) from my_stu);
表子查詢
需求:找出每個班中最高的一個學生
1.確定數據源:先將學生按照身高進行降序排序
select * from my_stu order by height desc;
2.從每個班選出第一個學生:
select * from my_stu group by c_id;
表子查詢:from 子查詢,得到的結果作爲from的數據源
select * from (select * from my_stu order by height desc)as student group by c_id;