SQL 使用子查詢

2021-09-10 09:30:14 字數 2422 閱讀 4614

sql還允許建立子查詢,巢狀再其他查詢中的查詢。下面舉幾個栗子來理解一下:

現在結合1;2這兩個查詢,把第乙個查詢(返回訂單號的那乙個)變為子查詢

select cust_id from orders

where order_num in(

select order_num from orderitems where prod_id=

'rgan01'

);

+

----

----

----

+| cust_id |+--

----

------+

|1000000004||

1000000005|+

----

----

----

+2 rows in

set(

0.00 sec)

現在結合1;2;3這三個查詢,更改為子查詢:

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'))

;

+

----

----

-------

+------

----

----

------+

| cust_name | cust_contact |+--

----

----

-----+

----

----

----

----

----

+| fun4all | denise l

. stephens |

| the toy store | kim howard |+--

----

----

-----+

----

----

----

----

----

+2 rows in

set(

0.01 sec)

注意對於能巢狀的子查詢的數目沒有限制,不過再實際使用時由於效能的限制,不能巢狀太多的子查詢。

注意:只能是單列

如果不採用`完全限定列名,dbms會認為要對orders表中的cust_id自身進行比較。

select

count(*

)from orders where cust_id = cust_id;

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

----

----

-----+

----

----

----+--

------+

| fun4all |in|

5|| fun4all |az|

5|| kids place |oh|

5|| the toy store |il|

5|| village toys |mi|

5|+--

----

----

-----+

----

----

----+--

------+

5 rows in

set(

0.00 sec)

雖然子查詢再構造這種select語句時極有用,但必須注意限制有歧義的列。

注意:完全限定列名

10 使用子查詢 SQL

利用子查詢進行過濾 普通查詢 select order num from orderitems where prod id rgan01 輸出 order num 20007 20008 select cust id from orders where order num in 20007,2000...

SQL多條件查詢子查詢SQL多條件查詢子查詢

多條件搜尋時where 1 1並不高效,如果使用這種方法,在資料庫中會做全表查詢 對每行資料都進行掃瞄比對 會無法使用索引等優化查詢的策略,建立的索引會暫時失效。case函式 case必須和end一起使用,下接when then select 數學成績 case when math 100 then...

mysql sql 子查詢語句 SQL子查詢

子查詢或內部查詢或巢狀查詢在另乙個sql查詢的查詢和嵌入式where子句中。子查詢用於返回將被用於在主查詢作為條件的資料,以進一步限制要檢索的資料。子查詢可以在select,insert,update使用,而且隨著運算子如delete語句 in,between 等.這裡有一些規則,子查詢必須遵循 子...