2019-08-07
列出訂購物品tnt2
的所有客戶,應該怎樣檢索?
訂單表orders
中儲存訂單號、客戶id
、訂單日期;各訂單的物品儲存在相關的orderitems
表中。
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 |
+----------------+--------------+
2rows
inset
(0.07 sec)
在select
語句中,子查詢總是從內向外處理。為了執行上述select
語句,mysql
實際上必須執行3條select
語句。最裡邊的子查詢返回訂單號列表,此列表用於其外面的子查詢的where
子句。外面的子查詢返回客戶id
列表,此客戶id
列表用於最外層查詢的where
子句。最外層查詢確實返回所需的資料。
在顯示where
子句中使用子查詢,應該保證select
語句具有與where
子句中相同數目的列。通常,子查詢將返回單個列並且與單個列匹配,但如果需要也可以使用多個列。
customers
表中每個客戶的訂單總數;訂單與相應的客戶id
儲存在orders
表中。
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|
+----------------+------------+--------+
5rows
inset
(0.03 sec)
在此例子中,該子查詢執行了5次,因為檢索出了5個客戶。
子查詢中的where
子句與前面使用的where
子句稍有不同,因為它使用了完全限定列名,它告訴sql
比較orders
表中的cust_id
與當前正從customers
表中檢索的cust_id
。這種型別的子查詢稱為相關子查詢(設計外部查詢的子查詢)。任何時候只要列名可能有多義性,就必須使用這種語法。
若不使用完全限定的列名會發生什麼情況?
mysql>
select cust_name,
-> cust_state,
->
(select
count(*
)->
from orders
->
where cust_id = cust_id)
as orders
->
from customers
->
order
by cust_name;
+----------------+------------+--------+
| cust_name | cust_state | orders |
+----------------+------------+--------+
| coyote inc.
| mi |5|
| e fudd | il |5|
| mouse house | oh |5|
| wascals |in|
5|| yosemite place | az |5|
+----------------+------------+--------+
5rows
inset
(0.00 sec)
顯然,返回的結果不正確。那麼,為什麼會這樣呢?有兩個cust_id
列,乙個在customers
中,另乙個在orders
中,需要比較這兩個列以正確地把訂單與它們相應的顧客匹配。**如果不完全限定列名,mysql
將假定你是對orders
表中的cust_id
進行自身比較。**而select count(*) from orders where cust_id = cust_id
;總是返回orders
表中的訂單總數(因為mysql
檢視每個訂單的cust_id
是否與本身匹配,當然,它們總是匹配的)。 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 根據子查詢的...
My SQL 使用子查詢
在關係型資料庫中,關係表是把資訊分解成多個表,一類資料乙個表,各表通過某些常用的值互相關聯。在乙個表中通常有乙個外來鍵,包含了和他有關係的表的主鍵,定義了兩個表之間的關係。這裡我們使用兩個表orders和orderitems為例,內容如下 可以看到這兩張表有關聯的是列order item列。想要獲得...
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 根據子查詢的...