Mysql學習歷程(14)-查詢

聯合查詢:將多次查詢(多條select語句)在記錄上進行拼接(字段不會增加)

語法:多條select 語句 構成;每一條select 語句獲取字段數必須嚴格一致(字段類型可以無關)

select 語句1  

union [union 選項]

select 語句2


union選項:all 保留所有  ;distinct  去重(整個重複),默認的;


聯合查詢的意義:查詢同一張表,但是需求不同,如查詢學生信息,男生身高升序,女生身高降序;

多表查詢,多張表結構完全一樣,保存的數據(結構也是一樣的);

在聯合查詢中,order by不能直接使用,需要對查詢語句使用括號才行;若要order by生效,必須搭配limit才行,limit使用限定的最大數即可 如99999;

create table stu_inf(
id int primary key auto_increment,
number varchar(10),
sex char(1),
age int ,
height  int
)charset utf8;

insert into stu_inf values(null,'001','女',17,158),
(null,'002','女',23,178),(null,'003','女',19,165),
(null,'004','男',22,183),(null,'005','男',17,173),
(null,'006','男',25,178);

(select * from stu_inf where sex='男' order by height asc limit 9999)
union
(select * from stu_inf where sex='女' order by height desc limit 9999)

子查詢:在某個查詢結果之上進行查詢;

子查詢有兩種分類方式:按位置分類和按結果分類;

按位置分類:子查詢在外部查詢中出現的位置;

from子查詢;where子查詢;exists子查詢;

按結果分類:根據子查詢得到的數據進行分類(理論上任何一個查詢得到的結果都可以理解爲二維表)

標量子查詢:子查詢得到的結果是一行一列;

查詢:子查詢得到的結果是一列多行;

量子查詢:子查詢得到的結果是一行多列;這三個出現在where之後

表子查詢:子查詢得到的結果是多行多列;這個出現在from之後;


標量子查詢:

select * from my_student where c_id=(select id from my_class where c_name='Java');

列子查詢

select * from my_student where c_id in (select id from my_class);
列子查詢返回結果比較多,一列多行,使用in作爲條件匹配;MYSQL中幾個類似的條件:all  ,some,any

=any 等於其中一個即可;  =all  爲全部;

!=any 與!=some 一個意思 


行子查詢

select * from my_student where (age,height)=(select max(age),max(height) from my_student);
(age,height)稱之爲元素;


表子查詢:子查詢返回的結果當作二維表使用;

select * from (select * from my_student order by height desc) as student group by c_id;


Exists子查詢:判斷某些條件是否滿足(通常是跨表),exists是接在where之後;exists返回的結果是0或者1;

select * from my_student where exists (select * from my_class);









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章