SQL開發例項和優化

2021-09-22 19:04:04 字數 2045 閱讀 1404

找出連續的資料 如1,2,3,48,50,51,52,53,67,68

找出連續的數字的起點和重點

1,348,48

51,53

67,68

create table test.range_problem(

a int not null,

primary key (a));

insert into test.range_problem values(1);

insert into test.range_problem values(2);

insert into test.range_problem values(3);

insert into test.range_problem values(48);

insert into test.range_problem values(50);

insert into test.range_problem values(51);

insert into test.range_problem values(52);

insert into test.range_problem values(53);

insert into test.range_problem values(66);

insert into test.range_problem values(67);

--思路1 找最後乙個不連續的數

select t1.a

from test.range_problem t1

where not exists

(select a

from test.range_problem t2

where t2.a -1 = t1.a

)--思路2  找所有行對應的結束值

select row_number()over(order by tbase.a) id

,tbase.a

,(select min(a)

from test.range_problem t1

where not exists

(select a

from test.range_problem t2

where t2.a -1 = t1.a

)and t1.a >= tbase.a  --t1.a 是3,48,53,67 tbase.a 是每行的值

) a_end

from test.range_problem tbase

--思路3 分組後找出所有連續的起始值和結束值

select min(a) a_start, a_end

from(

select row_number()over(order by tbase.a) id

,tbase.a

,(select min(a)

from test.range_problem t1

where not exists

(select a

from test.range_problem t2

where t2.a -1 = t1.a

)and t1.a >= tbase.a  --t1.a 是3,48,53,67 tbase.a 是每行的值

) a_end

from test.range_problem tbase

) tgroup by t.a_end

--對上面語句的優化

with pot as(

select a

from test.range_problem t

where not exists

( select a

from test.range_problem tc

where tc.a -1 = t.a)

)select tbase.a a_start,(select min(a)

from  pot t

where tbase.a <= t.a 

) a_end

from test.range_problem tbase

sql優化例項

1.盡量不生成子表或者將子表的資料量控制到最小 子表只能順序讀取,沒有任何索引 原有sql from select task id,user id from mtcrm task.item where status 0 and is deleted 0 and is archived 0 item ...

sql 查詢優化例項

語句1 select account.alias,sum amount from expense,account where date 20101101 and date 20101131 and expense.act id account.act id group by expense.act ...

SQL優化例項 思路分析

一sql優化思路 乙個真實具體的sql優化思路 一般都看預估的執行計畫,比如遇到乙個sql執行計畫很長,很複雜,從計畫中沒有看到返回行數多,cost高或連線方式錯誤的地方,沒有明顯瓶頸,但整體邏輯讀很高,執行很慢。這時就可以去看真實的執行計畫,並檢視真實計畫裡邏輯讀cr最多的步驟。可以做個10046...