有时候碰到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、遇到换行的情况,第二行开始用逗号开始。这样的好处时不查询某一列,把那一列删掉,直接选中删除,同时可读性也会更好。