MySQL必知必會十四 使用子查詢

2021-10-06 14:43:39 字數 1894 閱讀 1228

現在,假如需要列出訂購物品tnt2的所有客戶,應該怎樣檢索?下面列出具體的步驟。

檢索包含物品tnt2的所有訂單的編號。

檢索具有前一步驟列出的訂單編號的所有客戶的id。

檢索前一步驟返回的所有客戶id的客戶資訊。

上述每個步驟都可以單獨作為乙個查詢來執行。可以把一條select語句返回的結果用於另一條select語句的where子句。

mysql>

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=

'tnt2'))

;+----------------+--------------+

| cust_name | cust_contact |

+----------------+--------------+

| coyote inc.

| y lee |

| yosemite place | y sam |

+----------------+--------------+

對於能巢狀的子查詢的數目沒有限制,不過在實際使用時由於效能的限制,不能巢狀太多的子查詢。雖然子查詢一般與in操作符結合使用,但也可以於測試等於(=)、不等於(<>)等。

列必須匹配:在where子句中使用子查詢(如這裡所示),應該保證select語句具有與where子句中相同數目的列。

mysql>

select cust_name, cust_state,(-

>

select

count(*

)from orders where orders.cust_id = customers.cust_id)

as orders from customers order

by cust_name;

+----------------+------------+--------+

| cust_name | cust_state | orders |

+----------------+------------+--------+

| coyote inc.

| mi |2|

| e fudd | il |1|

| mouse house | oh |0|

| wascals |in|

1|| yosemite place | az |1|

+----------------+------------+--------+

子查詢中的where子句與前面使用的where子句稍有不同,因為它使用了完全限定列名。下面的語句告訴sql比較orders表中的cust_id與當前正從customers表中檢索的cust_id

where orders.cust_id = customers.cust_id
相關子查詢(correlated subquery) 涉及外部查詢的子查詢。

這種型別的子查詢稱為相關子查詢。任何時候只要列名可能有多義性,就必須使用這種語法(表名和列名由乙個句點分隔)。

MySQL必知必會 第十四章 使用子查詢

子查詢總是從內向外處理 列出訂購tnt2的全部客戶資訊 select from customers where cust id in select cust id from orders where order num in select order num from orderitems wher...

MySQL必知必會 十四 組合查詢

開始線 mysql也允許執行多個查詢,並將結果作為單個查詢結果集返回,這些組合查詢通常稱為並或復合查詢 有兩種基本情況,其中需要使用組合查詢 1.在單個查詢中從不同的表返回類似結構的資料 2.對單個表執行多個查詢,按單個查詢返回資料 可用union操作符來組合數條sql查詢 查詢 小於等於5的所有物...

mysql必知必會 mysql必知必會(四)

十四 理解子查詢 1 通過子查詢過濾 這本書在所有的章節都關連到了資料庫表,訂單資料是儲存在兩個表中,orders表儲存著 訂單號碼 顧客id和訂單日期。個人的訂單列表關連著orderitems表,訂單表沒有儲存顧客資訊,它只是儲存著顧客id,這實際的顧客資訊是儲存在customers表中。現在假設...