11 使用子查詢

2022-09-02 09:57:07 字數 2927 閱讀 6210

1.

子查詢查詢

(query)

:任何sql

語句都是查詢,但此術語一般指

select

語句。子查詢

(subquery)

:巢狀在其他查詢中的查詢。

2.利用子查詢進行過濾

假設需要列出訂購物品

'rgan01'

的所有顧客,檢索步驟為:

(1)檢索包含物品

rgan01

的所有訂單的編號;

(2)檢索具有前一步驟列出的訂單編號的所有顧客的id;

(3)檢索前一步驟返回的所有顧客

id的顧客資訊。

輸入:select order_num

from orderitems

where prod_id= 'rgan01'

輸出:

現在知道了包含要檢索物品的訂單下一步查詢與訂單

20007

和20008

相關的顧客

id。利用

in子句,輸入:

select cust_id

from orders

where order_num in (20007, 20008);

輸出:結合這兩個查詢,把第乙個查詢變為子查詢,輸入:

select cust_id

from orders

where order_num in (select order_num

from orderitems

where prod_id= 'rgan01');

輸出:

在select

語句中,子查詢總是從內向外處理。把子查詢分解為多行並進行適當的縮排,能極大地簡化子查詢的使用。

現在得到了訂購訂單

rgan01

的所有顧客的

id,下一步是檢索這些顧客

id的顧客資訊。檢索兩列的

sql語句如下。

輸入:select cust_name, cust_contact

from customers

where cust_id in ('1000000004' ,'1000000005');

輸出:

可以把其中的

where

子句轉換為子查詢,而不是硬編碼這些顧客id。

輸入:select cust_name, cust_contact

from customers

where cust_id in (select cust_id

from orders

where order_num in (select order_num

from orderitems

where prod_id= 'rgan01'));

輸出:

注意:作為子查詢的

select

語句只能查詢單個列

3.作為計算字段使用子查詢

使用子查詢的另一方法是建立計算字段。

假設需要顯示

customers

表中每個顧客的訂單總數。訂單與相應的顧客

id儲存在

orders

表中。使用

select count(*)

對顧客1000000001

的訂單進行計數,輸入:

select count(*) as orders

from orders

where cust_id = '1000000001';

輸出:要對每個顧客執行

count(*)

,應該將其作為乙個子查詢。

輸入:select cust_name,

cust_state,

(select count(*)

from orders

where orders.cust_id = customers.cust_id) as orders

from customers

order by cust_name

輸出:

此select

語句對customers

表中每個顧客返回三列:

cust_name

、cust_state

和orders

。子查詢中

where

子句使用了完全限定列名,指定表名和列名,並用乙個句點分隔:

orders.cust_id

和customers.cust_id

。在有可能混淆列名時必須使用這種語法,若不採用完全限定列名,

dbms

會對orders

表中cust_id

自身進行比較。

輸入:select cust_name,

cust_state,

(select count(*)

from orders

where cust_id = cust_id) as orders

from customers

order by cust_name;

輸出:

使用子查詢

2019 08 07 列出訂購物品tnt2的所有客戶,應該怎樣檢索?訂單表orders中儲存訂單號 客戶id 訂單日期 各訂單的物品儲存在相關的orderitems表中。mysql select cust name,cust contact from customers where cust id ...

SQL必知必會 第11課 使用子查詢

任何sql語句都是查詢,但此術語一般指select語句。sql還允許建立子查詢,即巢狀在其他查詢中的查詢。列出訂購物品rgan01的所有顧客 對於能巢狀的子查詢的數目沒有限制,不過由於效能的限制,不能巢狀太多的子查詢。列出customers表中每個顧客的訂單總數 其中orders是乙個計算字段,它是...

mysql update使用子查詢

今天我像以前操作oracle寫了乙個update sql update device user a set a.scene id null where a.id not in select min t.id from device user t group by t.device id 根據子查詢的...