SQL优化查询是否存在记录

一、使用count

当我们查询是否存在记录时也会使用select count(*) 或者使用select  count(1)来查询,比如在注册新用户时,需要手机号统一,判断是否该手机号已经注册

--sql
select count(*) from sa_user where phone = '18211009606'

--java
int nums = dao.countByPhone;
if (nums > 0) {
 // 大于0,表示存在该手机号
} else {
 // 小于0, 表示不存在
}

 像这种需要判断结果为存在,不存在,或者有,没有的sql查询,需要每次查询count,可以优化为如下

二、使用limit 1

--sql
select 1 from sa_user where phone = '18211009606' limit 1

--java
int nums = dao.countByPhone;
if (nums != null) {
 // 大于0,表示存在该手机号
} else {
 // 小于0, 表示不存在
}
以上sql不再使用count,而是使用limit 1来查询,让数据库只要遇到一条记录就返回结果,不需要再继续查询该条件的count数量
posted @ 2021-10-08 10:09  木马不是马  阅读(493)  评论(0编辑  收藏  举报