欢迎投稿

今日深度:

常见SQL编写和优化,

常见SQL编写和优化,


常见的SQL优化方式

select id from t where num is null  

可以在num上设置默认值0,确保表中num列是否存在null值,然后这样查询:

select id from t where num = 0  

如:

select id from t where num = 10 or num = 20 

可以这样查询:

select id from t where num=10   
union all   
select id from t where num=20   

对于union, 优先使用union all, 避免使用union。

UNION 因为会将各查询子集的记录做比较,故比起UNION ALL ,通常速度都会慢上许多。

一般来说,如果使用UNION ALL能满足要求的话,务必使用UNION ALL。

select id from t where num in (1,2,3)   

对于连续的数值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3  
select id from t where name like '%abc%'    
select id from t where num / 2 = 100    

应改为:

select id from t where num = 100 * 2    
select id from t where substring(name,1,3)='abc'--name以abc开头的id 

应改为(like 统计第6点):

select id from t where name like 'abc%' 
select col1,col2 into #t from t where 1=0   

这类代码不会返回任何结果集,但是会消耗系统资源的,应改成这样:

create table #t(...)    

如果查询的两个表大小相当,那么用in和exists差别不大,

如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

select num from a where num in(select num from b)   

用下面的语句替换:

select num from a where exists(select 1 from b where num=a.num) 

参考:https://blog.csdn.net/jie_liang/article/details/77340905
https://blog.csdn.net/weixin_40792878/article/details/81071584

www.htsjk.Com true http://www.htsjk.com/Mysql/39622.html NewsArticle 常见SQL编写和优化, 常见的SQL优化方式 select id from t where num is null 可以在num上设置默认值0,确保表中num列是否存在null值,然后这样查询: select id from t where num = 0 如: select id from t w...
相关文章
    暂无相关文章
评论暂时关闭