MySQL查找是否存在

1.使用count()

当需要查询数据是否存在时,一般会使用count函数,统计其个数,用法如下:

select count(1) from user where a = 1

在java中判断数量是否大于0即可:

int num = userDao.countUser(params);  
if ( num > 0 ) {  
  //存在时... 
} else {  
  //不存在时...
}  

这种方式固然可以,但也有更好的方式,是使用limit。

2.使用limit

select 1 from table where a = 1 limit 1  

这种方式让数据库查询时遇到一条就返回,无需再继续查找还有多少条,提高了查询的效率。

在java中判断是否为空即可:

Integer exist = userDao.existUser(params);  
if ( exist != NULL ) {  
  //存在时...
} else {  
  //不存在时...
}
原文地址:https://www.cnblogs.com/zys2019/p/15541349.html