有時候碰到Sql很長,會出現很多不必要的問題。比如,寫了前面忘了後面,别名寫錯等問題。遵守一些編碼規範能有效避免這種問題。本篇文章會持續更新遇到問題就添加上去。
1、找個合适的編輯器。在編輯器裡面寫好然後在複制到程式裡面運作。我目前的做法是在notepad裡面建一個.sql檔案,然後在裡面進行編碼。
2、用縮進來區分表的層級結構。比如下面這個SQL。最先執行的是最裡面的括号,然後依次往外執行。這種情況下,縮進4個tab,先寫最裡面的括号裡面的代碼,然後縮進3個tab,寫外部一層的代碼,依次往外。
#15.1 按平均成績進行排序,顯示總排名和各科排名,Score 重複時合并名次
select
t3.*
,t1.rank_avg
,sum(case when t2.cid = '01' then t2.rank_course else null end) as c_01
,sum(case when t2.cid = '02' then t2.rank_course else null end) as c_02
,sum(case when t2.cid = '03' then t2.rank_course else null end) as c_03
from
(
select
s1.sid
,count(distinct s2.avg_score) + 1 as rank_avg
from
(
select
sid
,avg(score) as avg_score
from sc
group by sid
) s1
left join
(
select
sid
,avg(score) as avg_score
from sc
group by sid
) s2
on s1.avg_score<s2.avg_score
group by s1.sid
) t1
inner join
(
select
s1.sid
,s1.cid
,count(distinct s2.score) as rank_course
from sc s1
left join sc s2
on (s1.cid = s2.cid and s1.score<s2.score)
group by s1.cid,s1.sid
) t2
on t1.sid = t2.sid
right join
student t3
on t1.sid = t3.sid
group by t1.sid
order by t1.rank_avg;
3、按SQL的執行順序寫。同一層結構裡面sql的執行順序如下:from ->where->group by->having -> select->order by 。
4、遇到換行的情況,第二行開始用逗号開始。這樣的好處時不查詢某一列,把那一列删掉,直接選中删除,同時可讀性也會更好。