select語句的查詢結果是元組的集合,所以多個select語句的結果可進行集合操作。 集合操作主要包括並操作union、交操作intersect、差操作except。 注意, 參加集合操作的各查詢結果的列數必須相同;對應的資料型別也必須相同。 本示例中的資料表有student,sc
select語句的查詢結果是元組的集合,所以多個select語句的結果可進行集合操作。
集合操作主要包括並操作union、交操作intersect、差操作except。
注意,參加集合操作的各查詢結果的列數必須相同;對應的資料型別也必須相同。
本示例中的資料表有student,sc,course三個,資料表的具體內容請看:mysql資料庫中的exists和not
exists
union示例:
例子1.1
題目:查詢電腦科學系的學生及年齡不大於19歲的學生。
sql語句:
select * from student where sdept='cs' union
select * from student where sage<=19
查詢結果:
本查詢實際上是求計算機系的所有學生與年齡不大於19歲的學生的並集。
與它等效的sql語句是:
select * from student where sdept='cs' or sage<=19
注意:雖然這個兩個sql語句是等效的,但是本質上是不一樣的,第乙個sql語句是分別進行兩次select然後將結果取並集;第二個sql語句是直接進行了一次select語句查詢。
intersect示例:
mysql語句並不至此intersect,所以只能使用其替代語句
例子2.1
題目:查詢電腦科學系中年齡不大於19歲的學生。
對應的sql語句應該是:
select * from student
where sdept='cs'
intersect
select * from student
where sage<=19;
替代的sql語句:
select *
from student
where sdept = 'cs'
and sage <=19
查詢結果:
例子2.2
題目:查詢即選修了課程1又選修了課程2的學生。(就是查詢選修課程1的學生集合與選修課程2的學生集合的交集)
對應的sql語句應該是:
select sno from sc
where cno='1'
intersect
select sno from sc
where cno='2';
替代的sql語句為:
(使用in)
select sno
from sc
where cno = '1'
and sno
in (
select sno
from sc
where cno = '2'
或者為:
(使用exists)
select sno
from sc scx
where cno = '1'
and exists (
select sno
from sc scy
where cno = '2'
and scx.sno = scy.sno
查詢結果為:
或者為:
(使用join on)
select *
from sc scx
join sc scy on ( scx.cno = '1'
and scy.cno = '2'
and scx.sno = scy.sno )
except操作:
很不幸,mysql也不支援except操作,只能使用替代的語句。
例子3.1
查詢電腦科學系的學生與年齡不大於19歲的學生的差集。
對應的sql語句為:
select * from student where sdept='cs'
except
select * from student where sage<=19;
也就是查詢電腦科學系中年齡大於19歲的學生。
替換語句為:
(直接使用where,不得不說這麼做很簡單,但是意思上不是很好理解)
select *
from student
where sdept = 'cs'
and sage >19
查詢結果為:
或者替換語句為:
(使用not in)
select *
from student
where sdept = 'cs'
and sno not
in (
select sno
from student
where sage <=19
查詢結果為:
或者使用替換語句為:
(使用not exists)
select *
from student sx
where sdept = 'cs'
and not
exists (
select *
from student sy
where sy.sage <=19
and sx.sno = sy.sno
查詢結果為:
對集合操作結果的排序
order by子句只能用於對最終查詢結果排序,不能對中間結果排序。
任何情況下,order by子句只能出現在最後;對集合操作結果排序時,order by子句中用數字指定排序屬性。
下面是一種錯誤的寫法:
select * from student
where sdept='cs'
order by sno
union
select * from student
where sage<=19
order by sno;
正確的應該是:
select * from student
where sdept='cs'
union
select * from student
where sage<=19
order by 2;
輸出結果:
如果寫成:
select * from student
where sdept='cs'
union
select * from student
where sage<=19
order by 1;
輸出結果為:
mysql集合屬性 初步介紹MySQL中的集合操作
啥是集合操作?通常來說,將聯接操作看作是表之間的水平操作,因為該操作生成的虛擬表包含兩個表中的列。而我這裡總結的集合操作,一般將這些操作看作是垂直操作。mysql資料庫支援兩種集合操作 union distinct和union all。與聯接操作一樣,集合操作也是對兩個輸入進行操作,並生成乙個虛擬表...
mysql 集合 MySql集合查詢
select語句的查詢結果是元組的集合,所以多個select語句的結果可進行集合操作。集合操作主要包括並操作union 交操作intersect 差操作except。注意,參加集合操作的各查詢結果的列數必須相同 對應的資料型別也必須相同。本示例中的資料表有student,sc,course三個,資料...
mysq集合差操作 mysql幾個結果集集合操作命
眾所周知的幾個結果集集合操作命令,今天詳細地測試了一下,發現一些問題,記錄備考。假設我們有乙個表student,包括以下欄位與資料 drop table student create table student id int primary key,name nvarchar2 50 not nul...