首页 > 数据库 > > 少侠!如何写一手好 SQL ?
来源 | 编码砖家
链接 | cnblogs.com/xiaoyangjia/p/11267191.html
其实这是非常低级的错误,我不禁后背一凉,团队成员的技术水平亟待提高啊。改造这些SQL的过程中,总结了一些经验分享给大家,如果有错误欢迎批评指正。

select field_1,field_2 from table where id < #{prePageMinId} order by id desc limit 20,prePageMinId是上一页数据记录的最小ID。虽然当时查询速度还凑合,随着数据不断增长,有朝一日必定不堪重负。max_used_connections / max_connections * 100% = 3/100 *100% ≈ 3%
show variables like '%max_connections%';show variables like '%max_user_connections%';
[mysqld]max_connections = 100max_used_connections = 20
如果长度能够满足,整型尽量使用tinyint、smallint、medium_int而非int。
如果字符串长度确定,采用char类型。
如果varchar能够满足,不采用text类型。
精度要求较高的使用decimal类型,也可以使用BIGINT,比如精确两位小数就乘以100后保存。

is not null的判断。select loginname, nickname from member where login_name = ?
update status=0 FROMcoupon WHERE expire_date <= #{currentDate} and status=1;如果大量优惠券需要更新为不可用状态,执行这条SQL可能会堵死其他SQL,分批处理伪代码如下:int pageNo = 1;
int PAGE_SIZE = 100;
while(true) {
List<Integer> batchIdList = queryList('select id FROM `coupon` WHERE expire_date <= #{currentDate} and status = 1 limit #{(pageNo-1) * PAGE_SIZE},#{PAGE_SIZE}');
if (CollectionUtils.isEmpty(batchIdList)) {
return;
}
update('update status = 0 FROM `coupon` where status = 1 and id in #{batchIdList}')
pageNo ++;
}
select id from orders where amount != 100;如果金额为100的订单极少,这种数据分布严重不均的情况下,有可能使用索引。鉴于这种不确定性,采用union聚合搜索结果,改写方法如下:(select id from orders where amount > 100) union all(select id from orders where amount < 100 and amount > )
select id,product_name from orders where mobile_no = '13421800407' or user_id = 100;
(select id,product_name from orders where mobile_no = '13421800407') union(select id,product_name from orders where user_id = 100);
select o.id from orders o left join user u on o.user_id = u.id where u.level = 'VIP';
select id from order where date_format(create_time,'%Y-%m-%d') = '2019-07-01';
select id from order where create_time between '2019-07-01 00:00:00' and '2019-07-01 23:59:59';
SELECT *,它会进行全表扫描,不能有效利用索引。SELECT column FROM table WHERE field like '%keyword%';
SELECT column FROM table WHERE field like 'keyword%';
select * from orders order by id desc limit 100000,10 耗时0.4秒select * from orders order by id desc limit 1000000,10耗时5.2秒
select * from orders where id > (select id from orders order by id desc limit 1000000, 1) order by id desc limit ,10耗时0.5秒
select id from orders where id between 1000000 and 1000010 order by id desc耗时0.3秒

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3121051/ ,如需转载,请注明出处,否则将追究法律责任。