用分析函式優化標量子查詢

2021-06-19 03:49:15 字數 1135 閱讀 5319

原語句如下

select ii.*,

case

when (select count(1)

from ii

where ii.id > 0

and ii.flag = 2

and ii.i_code = ii.i_code

and ii.c_id not in

(select c_id

from c

where ig_name like '%停用%')) > 1 then

2else

1end as mulinv

from ii

where (ii.id > 0 and itemdesc like :1 and ii.isphantom <> :2)

and ii.c_id = :3

order by ii.i_code, ii.i_name, ii. d_id

經詢問 c.c_id是主鍵,這樣就可以改寫為left join

select *

from (select ii.*,

case

/*用分析函式代替標量自聯接*/

when (sum(case when flag = 2 and c.c_id is null then 1 end) over(partition by ii.i_code)) > 1 then

2else

1end as mulinv

from ii

/*因c.cid為主鍵,所以可改為left join而不必擔心主查詢資料會翻倍*/

left join c on (c.c_id = ii.c_id and c.ig_name like '%停用%')

/*為了保證分析函式視窗內資料與原標量範圍一致,這兒的過濾條件要保持一致*/

where ii.id > 0)

/*提取出原標量所需資料後再應用其它的過濾條件*/

where itemdesc like :1

and ii.isphantom <> :2

and ii.c_id = :3

order by ii.i_code, ii.i_name, ii. d_id;

mysql標量子查閱 MySQL 標量子查詢

mysql 標量子查詢 標量子查詢是指子查詢返回的是單一值的標量,如乙個數字或乙個字串,也是子查詢中最簡單的返回形式。乙個標量子查詢的例子如下 select from article where uid select uid from user where status 1 order by uid...

MySQL中的標量子查詢,列子查詢,行子查詢

標量子查詢,列子查詢,行子查詢都屬於where子查詢,也就是說都寫在where之後 標量子查詢 概念 子查詢得到的結果是乙個資料 一行一列 語法 select from 資料來源 where 條件判斷 select 欄位名 from 資料來源 where 條件判斷 查詢到的結果就只有乙個結果 案例 ...

在MySQL中使用子查詢和標量子查詢的基本用法

一 mysql 子查詢 子查詢是將乙個 select 語句的查詢結果作為中間結果,供另乙個 sql 語句呼叫。mysql 支援 sql 標準要求的所有子查詢格式和操作,也擴充套件了特有的幾種特性。子查詢沒有固定的語法,乙個子查詢的例子如下 select from article where uid ...