SQL 必知必會第十一課 使用子查詢

2021-10-10 18:19:53 字數 2262 閱讀 3664

select order_num from orderitems where prod_id =

'rgan01'

;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 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

count(*

)as orders from orders where cust_id =

1000000001

;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 cust_name,

cust_state,

(select

count(*

)from orders

where cust_id = cust_id)

as orders -- 錯誤,因為沒有限制列名

from customers

order

by cust_name;

## challenges

select cust_id from orders where order_num in

(select order_num from orderitems where item_price >=10)

;-- 1

select cust_id,

order_date

from orders

where cust_id in

(select cust_id from orderitems where prod_id =

'br01'

)order

by order_date;

-- 2

select cust_email

from customers

where cust_id in

(select cust_id from orders where cust_id in

(select cust_id from orderitems where prod_id =

'br01'))

;-- 3

## 第四題

select cust_id,

(select

sum(quantity * item_price)

-- sum和括號中不要有空格

from orderitems

where orderitems.order_num = orders.order_num

group

by order_num)

as total_ordered-- 第二步選出**

from orders

order

by total_ordered;

-- 第一步選出顧客id

## 第五題

select prod_name,

(select

sum(quantity)

from orderitems

where orderitems.prod_id = products.prod_id

group

by prod_id)

as quant_sold -- 找出賣掉的產品數量

from products;

-- 找出對應的產品名稱

注意點

子查詢只能查詢單列

列名要完全限定,錯誤例子見**

SQL必知必會筆記十一(使用子查詢)

select語句是sql的查詢。我們迄今為止所看到的所有select語句都是簡單查詢,即從單個資料庫表中檢索資料的單條語句。查詢 query 任何sql語句都是查詢。但此術語一般指select語句。sql還允許建立子查詢 subquery 即巢狀在其他查詢中的查詢。說明 mysql支援 如果使用my...

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

開始線 查詢 任何sql語句都是查詢。但此術語一般指select語句 列出訂購物品tnt2的所有客戶 1.檢索包含物品tnt2的所有訂單的編號 2.檢索具有前一步列出的訂單編號的所有客戶的id 3.檢索前一步返回的所有客戶id的客戶資訊 現在得到訂購tnt2的所有客戶的id,下一步是檢索這些客戶id...

MySQL必知必會 第十一章 使用資料處理函式

大多數sql實現支援以下函式 1 用於處理文字串的文字函式 如刪除or填充值,轉換大小寫等 2 用於在數值資料上進行算數操作的數值函式 3 用於處理日期和時間值並從這些之中提取特定成分的日期和時間函式 如返回兩個日期之差,檢查日期的有效性等 4 返回dbms正使用的特殊資訊 如返回使用者登入資訊,檢...