SQL 組合查詢

2021-07-11 11:27:17 字數 3116 閱讀 8793

如何利用union操作符將多條select語句組合成乙個結果集?

sql允許執行多個查詢(多條select語句),並將結果作為乙個查詢結果集返回。這些組合查詢通常稱為並(union)復合查詢(compound query)

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

在乙個查詢中從不同的表返回結構資料;

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

組合查詢

可用union操作符來組合數條sql查詢。利用union,可以給出多條select語句,將它們的結果組合成乙個結果集。

-- 需要illinois、indiana和michigan等美國幾個州的所有顧客的報表

-- 還想包括不管位於哪個州的所有的fun4all

-- 需求一

select cust_name, cust_contact, cust_email

from customers

where cust_state in ('il','in','mi');

-- 需求二

select cust_name, cust_contact, cust_email

from customers

where cust_name = 'fun4all';

-- 組合兩條語句

select cust_name, cust_contact, cust_email

from customers

where cust_state in ('il','in','mi')

union

select cust_name, cust_contact, cust_email

from customers

where cust_name = 'fun4all';

需求一結果顯示:

需求二結果顯示:

結果顯示:

這條語句由前面的兩條select語句組成,之間用union關鍵字分隔。union指示dbms執行這兩條select語句,並把輸出組合成乙個查詢結果集。

觀察顯示結果,使用union時,重複行會被自動去掉。事實上,如果想返回所有的匹配行,可以使用union all。

-- 返回所有項

select cust_name, cust_contact, cust_email

from customers

where cust_state in ('il','in','mi')

union

allselect cust_name, cust_contact, cust_email

from customers

where cust_name = 'fun4all';

結果顯示:

-- 使用where代替union

select cust_name, cust_contact, cust_email

from customers

where cust_state in ('il','in','mi')

or cust_name = 'fun4all';

結果顯示:

在這個簡單的例子中,使用union可能比使用where子句更為複雜。但對於較複雜的過濾條件,或者從多個表(而不是乙個表)中檢索資料的情形,使用union可能會使處理更簡單。

注: union幾乎總是完成與多個where條件相同的工作。union all為union的一種形式,它完成where子句完成不了的工作。如果確實需要每個條件的匹配行全部出現(包括重複行),就必須使用union all,而不是where。

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

-- 對前面union返回的結果進行排序:

select cust_name, cust_contact, cust_email

from customers

where cust_state in ('il','in','mi')

union

select cust_name, cust_contact, cust_email

from customers

where cust_name = 'fun4all'

order

by cust_name, cust_contact;

結果顯示:

order by雖然位於最後,但是他排序select返回的所有結果。

union規則union必須由兩條或兩條以上select語句組成,語句之間用union分隔(因此,如果組合四條select語句,將要使用三個union關鍵字)。

union中的每個查詢必須包含相同的列、表示式或聚集函式(不過,各列不需要以相同的次序列出)。

列資料型別必須相容:型別不必完全相同,但必須是dbms可以隱含轉換的型別(例如,不同的數值型別或不同的日期型別)。

SQL學習 組合查詢

多數sql查詢都只包含乙個或從多個表中返回資料的單條select語句。mysql也允許執行多個查詢 多條select語句 並將結果作為單個查詢結果集返回。這些組合查詢通常稱為並或復合查詢 有兩種情況需要使用組合查詢 可用union操作符來組合數條sql查詢。利用union,可給出多條select語句...

sql模糊查詢實現組合查詢

資料庫程式設計中經常遇到組合查詢的情況。例如,某公司資料庫裡有一張存放使用者資訊的表user info,它有多個字段 userid,id,name,age,address。其中userid是表的主碼,表示使用者的使用者號,該使用者號對每個使用者都是唯一的 id表示使用者省份證號。此時要對使用者資訊進...

SQL 子查詢與組合查詢

2.組合查詢 union union all 在 where 條件中某個值可以通知子查詢句表示 就是 select 鑲嵌select 語句select from table1 where id select id from table2 where name xx with as 相當於將 as 內...