sql查詢之巢狀查詢

2021-08-27 19:43:16 字數 1334 閱讀 4199

巢狀查詢也叫子查詢,乙個select語句的查詢結果能夠作為另外乙個語句的輸入值。子查詢不但可以出現在where子句中,也能出現在from中作為乙個臨時表使用,而且還可以出現在select list中,作為乙個欄位值來返回。

1、單行子查詢:單行子查詢的返回值只有一行資料。可以再主查詢語句的條件語句中引用子查詢返回的結果,但須使用單行比較符合(=、>、<、>=、<=、<>)來進行比較。

例如:select e.*  from emp e

where deptno=(select dempno from dept where d_name='product');

2、多行子查詢:多行子查詢即是子查詢的結果為多行資料 。當主查詢語句的條件語句中引用子查詢結果時必須使用多行比較符號(in , all , any)來進行比較。

注意:all和any需要和單行比較符

(=、>、<、>=、<=、<>)

結合使用。all必須要符合子查詢的所有值,any符合子查詢結果中的任何乙個值即可。

例如:--查出分數比所有名字為『aa』的人分數都高的人

select stname from student s1

where s1.score > all(select score from score where p_name='aa');

--查出分數比名字為『aa』的人中任意乙個分數高的

select stname from student s1

where s1.score > any(select score from score where p_name='aa');

3、多列子查詢:當是單行多列的子查詢時,主查詢語句的條件語句中引用子查詢結果時可用單行比較符號(

=、>、<、>=、<=、<>

)來進行比較;當時多行多列子查詢時,主查詢語句的條件語句中引用子查詢結果時必須用多行比較符號(

in , all , any

)來進行比較。

例如:select dempno,ename,job,sal

from emp

where (deptno,sal) in (select deptno,max(sal) from emp group by dempno);

4.在select list中巢狀子查詢的使用方法:

例如:--主查詢中每掃瞄一行就會遍歷一次table_name1表,找出主表id和

table_name1中的filed_id相等的

select d.* ,(select r.cap_id from table_name1 r

where r.filed_id =d. id ) as capid

from table_name2 d

SQL巢狀查詢

訂單表orders 顧客表 customers 訂單商品表orderitems 列出訂購物品rgan01的所有顧客 select cust name,cust contact from customers where cust id in select cust id from orders whe...

SQL 多表查詢 巢狀查詢

多表查詢 1 結構 select from where 2 笛卡爾積查詢 select from student,course select from student,sdept 3 查詢每個學院的學生情況 select from student,sdept where student.deptno...

sql鑲嵌查詢 SQL 查詢巢狀使用

示例表如下 create table it student id int primary key auto increment,主鍵id name varchar 20 姓名 gender enum male female 性別 class id tinyint unsigned,班級號 age i...