MySQL的日常使用

呐,作为后台程序猿,必不可少的要与数据库打交道,所以今天记录下平时工作中遇到的一些sql问题。
数据库操作,大家用的最多的应该就是select了,使用select我们要记住一个原则:尽量使每次查询的结果集够小!
比如一个嵌套查询A(1000)B(100)C(10),括号中为每个查询结果的行数,如果我们按ABC来执行,那么显然比按CBA执行耗时更长。
为了执行效率的提高,正常都会给某些关键字段加上索引,但是有些查询是不走索引的,这种情况要尽量使用替代方案。

不走索引替代方案描述
select id from t where num is nullselect id from t where num = 0给字段设置默认值
select id from t where num=10 or name = ‘admin’select id from t where num = 10 union select id from t where name = ‘admin’必须要所有 or 连接的字段都有索引才会走索引
select id from t where num in(1,2,3)select id from t where num between 1 and 3in 条件连续
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)避免使用in/not in
select id from t where name like ‘%abc%’select id from t where name like ‘abc%’使用右模糊

除了以上,还有关于查询条件左侧有函数和运算操作的情况,这里针对日期详细说一下:
很多同学根据日期来查询的时候通常会这样写:
select * from tableA where fieldDate>‘20170101’
很显然,这样是能查出结果的,但是这样是不走日期上的索引的,因为数据库会默认把fieldDate转成varchar然后再与’20170101’比较。
还有同学这样写:
select * from tableA where DATE_FORMAT(fieldDate, ‘%Y-%m-%d’) >DATE_FORMAT(20170101, ‘%Y-%m-%d’)
这样也是不对的,我们要避免在字段上加处理函数。
正确的写法应该是这样:
select * from tableA where fieldDate>STR_TO_DATE(20170101, ‘%Y-%m-%d’)

几个sql:
IF函数是一个很常用也很重要的函数,
select if(isnull(query_times), 1, query_times+1) as m1
select if(query_times>0, true, false) as m2
与之相对应的还有case when,适合多种分支的情况。

一个表中根据字段guid有重复记录,怎么把这些记录找出来?
select * from tableB where guid in (select guid from tableB where status=1 group by guid having count(*) > 1)

mysql中,根据某个字段倒序排序,如果存在行数该字段为null,那么这些行数是显示在最后的:
SELECT * FROM app_feedback ORDER BY reply_time DESC
这里写图片描述
当我们在页面展示时,我们既希望保持倒序排序,又希望把有null值的显示在最前面,方便操作人员优先操作这些为null的记录,此时可以这样:
SELECT * FROM app_feedback ORDER BY -reply_time ASC
这里写图片描述

多表合并,union和union all,前者自动去掉重复记录,后者保留。
feedback_user表中存在type字段,type有1和2两种值的可能。
这里写图片描述
现在需要统计出每个feedback_id对应的type等于1和2的记录数:
SELECT feedback_id,SUM(oppo),SUM(supp) from (
SELECT feedback_type,feedback_id,COUNT() as oppo,0 as supp from app_feedback_user where feedback_type=‘2’ GROUP BY feedback_id,feedback_type union
SELECT feedback_type,feedback_id,0 as oppo,COUNT(
) as supp from app_feedback_user where feedback_type=‘1’ GROUP BY feedback_id,feedback_type) as ta
GROUP BY feedback_id
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值