零基礎入門 SQL 系列之(七)組合

2021-10-17 19:09:45 字數 2924 閱讀 8067

前面講到的 sql 查詢只包含從乙個或多個表中返回資料的單條select語句。sql 也允許執行多個查詢(多條select語句),並將結果作為乙個查詢結果集返回,這些組合查詢通常稱為復合查詢。

主要有兩種情況需要使用組合查詢:

1.對乙個表執行多個查詢,按乙個查詢返回資料。

2.從不同的表返回資料。

組合查詢使用關鍵字union,使用union很簡單,所要做的只是給出每條select語句,在各條select語句之間放上關鍵字union

舉個例子,我們根據訂單的日期將訂單歸到相應的月份。

select order_num,cust_id,

'jan' mon

from orders

where order_date >=

'2012-01-01 00:00:00'

and order_date <=

'2012-01-31 23:59:59'

union

select order_num,cust_id,

'feb' mon

from orders

where order_date >=

'2012-02-01 00:00:00'

and order_date <=

'2012-02-28 23:59:59'

;

這個例子將從同乙個表裡查詢到的兩個結果組合成乙個結果。

我們還可以將從不同表中查詢到的結果組合在一起進行返回。

例如:

select vend_name

from vendors

union

select cust_name

from customers;

在這個例子中,我們將**商的名字和客戶的名字組合在一起進行返回。

union非常容易使用,但在進行組合時需要注意幾條規則:

1.union必須由兩條或兩條以上的select語句組成,語句之間用關鍵字union分隔。

2.union中的每個查詢必須包含相同數量的列。

3.列資料型別必須相容:型別不必完全相同,但必須是 dbms 可以隱含轉換的型別。

union會在最後的結果中剔除重複的行。

select cust_name, cust_address

from customers

where cust_state in

('il'

,'in'

,'mi'

)union

select cust_name, cust_address

from customers

where cust_name =

'fun4all'

如果想不剔除重複的行,我們可以使用union all

select cust_name, cust_address

from customers

where cust_state in

('il'

,'in'

,'mi'

)union

allselect cust_name, cust_address

from customers

where cust_name =

'fun4all'

從結果中我們可以看出,沒有剔除重複的行。

對組合查詢結果排序:

同樣的,我們可以對組合查詢結果進行排序。在對組合查詢結果進行排序時,只能使用一條order by子句,它必須位於最後一條select語句之後。對於結果集,不存在用一種方式排序一部分,而又用另外一種方式排序另一部分的情況,因此不允許使用多條order by子句。

例如我們對剛才查詢的結果進行排序:

select cust_name, cust_address

from customers

where cust_state in

('il'

,'in'

,'mi'

)union

select cust_name, cust_address

from customers

where cust_name =

'fun4all'

order

by cust_name;

本講講述了如何用union操作符來組合select語句。利用union,可以把多條查詢的結果作為一條組合查詢返回,不管結果中有無重複。另外講述了如何對組合查詢返回的結果進行排序。

本系列目錄:

零基礎入門 sql 系列之(一)查詢資料

零基礎入門 sql 系列之(二)排序

零基礎入門 sql 系列之(三)過濾資料

零基礎入門 sql 系列之(四)內建函式

零基礎入門 sql 系列之(五)資料彙總

零基礎入門 sql 系列之(六)表連線

零基礎入門 sql 系列之(七)組合

零基礎入門 sql 系列之(八)插入、更新、刪除

零基礎入門 sql 系列之(九)建立和操作表

零基礎入門 sql 系列之(十)檢視

零基礎入門 SQL 系列之(八)插入 更新 刪除

insert用來將行插入到資料庫表中。插入有幾種方式 insert into customers values 1000000006 toy land 123 any street new york ny 11111 usa jordan jordan gmail.com 插入到新行中的值由valu...

Python零基礎入門 基礎(七) 函式

函式是指將一組語句的集合通過乙個名字 函式名 封裝起來,要想執行這個函式,只需呼叫其函式名即可。特性 減少重複 使程式變的可擴充套件 使程式變得易維護 def calc x,y 函式名 res x y return res 返回函式執行結果 c calc a,b 呼叫函式,結果賦值給c變數 prin...

零基礎入門 SQL 系列之(九)建立和操作表

sql 不僅可以用來操縱表中的資料,還可以對錶本身進行操縱,包括表的建立 更改和刪除。一般有兩種建立表的方法 我們以 customers 表的建立為例,建立語句如下 create table customers cust id char 10 not null cust name char 50 n...