在团队协作中,开发写的SQL往往要经过DBA审核才能上线。如果语句写得随意,不仅会被打回,还容易引发慢查询甚至锁表。下面分享五个能让DBA认可的SQL技巧,帮你写出更专业的代码。

一、用exists代替in处理大集合
当子查询返回数据量较大时,in会导致外层表对每一个值都做一次比较,而exists只要命中就停止匹配,效率更高。
-- 不推荐 select * from orders where user_id in (select id from users where age > 30); -- 推荐 select o.* from orders o where exists (select 1 from users u where u.id = o.user_id and u.age > 30);
二、避免字段上的函数导致索引失效
在where条件中对索引列使用函数,会让数据库无法走索引,变成全表扫描。
-- 索引失效写法 select * from log where date(create_time) = '2023-01-01'; -- 推荐写法 select * from log where create_time >= '2023-01-01' and create_time < '2023-01-02';
三、只查询需要的列
使用select *会读取多余字段,增加IO和内存开销,也可能让覆盖索引失效。明确列出字段名是DBA提倡的习惯。
-- 不推荐 select * from product where status = 1; -- 推荐 select id, name, price from product where status = 1;
四、大表删除采用分批提交
一次性delete大量数据会占用长事务并锁表,DBA通常要求分批操作。
delete from audit_log where create_time < '2022-01-01' limit 1000; -- 循环执行直到影响行数为0
五、学会看执行计划
在语句前加explain,观察type、key、rows等字段,确认是否走了索引,这是和DBA沟通慢查询时的通用语言。
explain select id, name from user where phone = '13800000000';
把上面五个技巧用熟,你提交的SQL会更清爽,DBA审核时也会更省心。写代码时多想一步数据库的负担,合作自然更顺畅。