聯(lián)合查詢
????????基本語法:
????????????????????????select 語句1
????????????????????????union [union 選項(xiàng)]
????????????????????????select 語句2……
????????union 選項(xiàng)
????????????????????????all:保留所有窿春,不管重復(fù)
????????????????????????distinct:去重拉一,默認(rèn)的
-- 聯(lián)合查詢
select * from my_class
union -- 默認(rèn)去重
select * from my_class;
select * from my_class
union all -- 不去重
select * from my_class;
select id,c_name,room from my_class
union all -- 不去重
select name,number,id from my_student;
-- 需求:男生升序采盒,女生降序(年齡)
(select * from my_student where sex='男' order by age asc limit 9999999)
union
(select * from my_student where sex='女' order by age desc limit 9999999);
子查詢
按位置分類
?????from子查詢
??where子查詢
?exists子查詢
按結(jié)果分類(不用背,了解舅踪,不考)
?標(biāo)量子查詢:一行一列
???列子查詢:一列多行
行子查詢:多列一行/多行多列
?表子查詢:多行多列
-- 標(biāo)量子查詢
select * from my_student where c_id=(select id from my_class where c_name='Python1910');-- id一定只有一個值(一行一列)
列子查詢
????????=any等價于in; -- 其中一個即可
????????any等價于some; -- 二者是一樣的
????????=all為全部
-- 列子查詢(in偶爾用)
select * from my_student where c_id in(select id from my_class);
-- any,some,all——肯定(不常用纽甘,了解)
select * from my_student where c_id=any(select id from my_class);
select * from my_student where c_id=some(select id from my_class);
select * from my_student where c_id=all(select id from my_class);
-- any,some,all——否定(不常用良蛮,了解)
select * from my_student where c_id!=any(select id from my_class);-- 所有的結(jié)果(NULL除外)
select * from my_student where c_id!=some(select id from my_class);-- 所有的結(jié)果(NULL除外)
select * from my_student where c_id!=all(select id from my_class);--(NULL除外)
-- 查詢年齡最大且身高最高
select * from my_student where
age=(select max(age) from my_student)
and
height=(select max(height) from my_student);
-- 行子查詢
select * from my_student where
-- (age,height)稱為行元素
(age,height)=(select max(age),max(height) from
my_student);
select * from my_student order by age desc,height desc limit 1;-- 可能查詢結(jié)果不是預(yù)想的
-- 表子查詢
select * from my_student group by c_id order by height desc;-- 不符合要求(每個班取第一個再排序)
-- 插入學(xué)生
insert into my_student values
(null,'bc20200007','小紅','女',33,185,1);
-- 查找每個班身高最高的學(xué)生(加limit 9999999才能查出預(yù)想結(jié)果抽碌,有的不加也行,根據(jù)數(shù)據(jù)庫版本決定)
select * from (select * from my_student order by
height desc limit 9999999) as student group by c_id;-- 每個班選出第一個學(xué)生
exists子查詢
select exists(select * from my_student);
select exists(select * from my_student where id=100);
-- exists子查詢
select * from my_student where
exists(select * from? my_class);-- 是否成立
select * from my_student where
exists(select * from? my_class where id=3);
select * from my_student where
exists(select * from? my_class where id=2);