mysql 復合查詢

2021-08-16 11:15:35 字數 2564 閱讀 6317

mysql 的復合查詢或者巢狀查詢,有表兩張,要以 clrtheme 表兩張為表列,將 clrcolor 橫向列出,故選擇巢狀查詢。

mysql 復合巢狀查詢命令如下

select * from clrtheme as t1,  

( (select * from clrcolor where

`sort` = 0) as c1,

(select * from clrcolor where

`sort` = 1) as c2,

(select * from clrcolor where

`sort` = 2) as c3,

(select * from clrcolor where

`sort` = 3) as c4,

(select * from clrcolor where

`sort` = 4) as c5

) where

t1.clrthemeid = c1.clrthemeid

and t1.clrthemeid = c2.clrthemeid

and t1.clrthemeid = c3.clrthemeid

and t1.clrthemeid = c4.clrthemeid

and t1.clrthemeid = c5.clrthemeid

order

by t1.clrgroupid, t1.sort asc;

查詢結果將以 clrtheme 為主列,將 clrcolor 作為子列,根據條件得到結果。

這裡針對 clrcolor 的內查詢建議加條件,以提高效能。

select name,age from person 

where age >

( select age from person

where name = '孫權'

)

in巢狀查詢

in關鍵字用於where子句中用來判斷查詢的表示式是否在多個值的列表中。返回滿足in列表中的滿足條件的記錄。

select name from person 

where countryid in

( select countryid from country

where countryname = '魏國'

)

some 巢狀查詢

some在sql中的邏輯運算符號,如果在一系列比較中,有些值為true,那麼結果就為true。some的語法是:

《表示式》some(子查詢)

例子:

select name from person 

where countryid = some       --用等號和以下查詢到的值比較,如果與其中乙個相等,就返回

( select countryid from country

where countryname = '魏國'

)

all 巢狀查詢

all是sql中的邏輯運算子好,如果一系列的比較都為true,那麼結果才能為true。

《表示式》all(子查詢)

例子:

select name from person 

where countryid > all   --當countryid大於以下返回的所有id,此結果才為true,此結果才返回

( select countryid from country

where countryname = '魏國'

)

exists巢狀查詢

1、語法

exists是sql中的邏輯運算符號。如果子查詢有結果集返回,那麼就為true。exists代表「存在」的意義,它只查詢滿足條件的那些記錄。一旦找到第乙個匹配的記錄後,就馬上停止查詢。

其中子查詢是乙個首先的select語句,不允許有compute子句和into關鍵字。

exists 的意思是,子查詢是否有結果集返回。

例如:

select * from person

where

exists

( select

1 --select

0select

null 返回結果都一樣,因為這三個子查詢都有結果集返回,因此總是true

select * from person照常執行

)

但是如果子查詢中因為加了條件而沒有結果集返回,則主語句就不執行了:

select * from person

where

exists

( select * from person

where person_id = 100 --如果不存在person_id的記錄,則子查詢沒有結果集返回,主語句不執行

)

MySQL復合查詢

實際開發中往往資料來自不同的表,所以需要多表查詢。下面以乙個簡單的公司管理系統,有三張表emp,dept,salgrade來演示如何進行多表查詢。舉例 1.顯示雇員名,雇員工資以及所在部門的名稱。因為要查詢的資料來自兩個表,所以叫做多表查詢。select emp.ename,emp.sal,dept...

MySQL筆記 復合查詢 內外連線

集合查詢 子查詢 單行子查詢 select from emp where deptno select deptno from emp where ename smith 多行子查詢 in 查詢和10號部門的工作相同的雇員的名字,崗位,工資,部門號,但是不包含10自己的 select ename,jo...

MongoDB 復合查詢

復合查詢 and 並且 當查詢條件為多個欄位時,就會需要使用多欄位復合條件查詢。在查詢條件中指定多個字段條件,檢索出所有滿足條件的文件資料。eg 查詢person集合中年齡 age 大於30歲,並且名字 name 為 lucy 的資料。db.person.find 復合查詢 or 或 當有多個查詢條...