首页 > 技术文章 > 编写SQL语句时的注意事项

pdxbb 2019-05-18 16:53 原文

1.编写SQL语句时,不要习惯性编写select *,只返回自己想要的字段

2.连接多表时使用表的别名并在每个字段前面加上别名,这样可以减少解析时间并且由字段歧义引起的语法错误

3.减少重复的工作,例如减少数据类型转化的次数;一次update可以完成的操作,不要使用多个update

4.若语句复杂,可使用临时表或变量来分布查询;若需要多次来用到同一部分数据,可以用临时表来暂存这部分数据

什么是相关子查询?

如果子查询的条件中使用了其外层的表的字段,这种子查询就叫作相关子查询。

相关子查询可以用IN、NOT IN、EXISTS、NOT EXISTS引入。

(1)可以改用LEFT JOIN来代替NOT INNOT EXISTS的相关子查询

select A.name from A where p_id not in(where p_id from B where type='physic')

可以改成   select A.name from A left join B on B.type='physic' and A.p_id=B.p_id where B.p_id is null

(2)若子查询没有重复,可以用inner join 来代替in ,exists

select A.name from A  where p_id in(where p_id from B where type='physic')

可以改成  select distict A.name from A inner join B on A.p_id=B.p_id and B.type='physic'

(3) IN的相关子查询用EXISTS代替

(4) 不要用COUNT(*)的子查询判断是否存在记录,最好用LEFT JOIN或者EXISTS

select aid from A where (select count(*) from B where B.bid=A.aid)=0

可以改成  select aid from A left join B on A.p_id=B.p_id and B.id is null

或  select aid from A where exists (select 1 from B where B.bid=A.aid)
注:inner join 是内连接,INNER JOIN 关键字在表中存在至少一个匹配时返回行,A表中的行在B表中至少有一个进行匹配,才会返回结果

       left join 与right join是外连接

再写下sql的left joinright joininner join之间的区别

  left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 ,右表中没有的值会补null
  right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录,左表中没有的值会补null
  inner join(等值连接) 只返回两个表中联结字段相等的行,没有null的情况

 4.查询语句时尽量使用索引

使用索引是需要注意的几点

(1)不对索引字段进行计算,而是做变换

select id from where num/2=100
应改为:
select id from where num=100*2

(2)避免对索引字段进行格式转换

(3)避免对索引字段使用函数

日期字段的例子:
where datediff(day, 日期,'2010-06-30')=0
应改为:where 日期='2010-06-30'

(4)不要对索引字段进行多字段连接

where name+'. '+fname='wei,com'
应改为:
where name='wei' AND fname='com'

5.写存储过程,如果语句比较长的话,最好用标记符标开,这样可读性会很好

这些是我看大佬博客时自己做的一些整理

推荐阅读