mysql中判断记录是否存在的两种方式

一、使用count()聚合函数

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

select count(1) from t_sys_user where username = "zhangsan"

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

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

二、使用limit 1

select 1 from t_sys_user where username = 'zhangsan' limit 1

如果存在,则返回1,如果不存在,则返回null,在java中判断是否为空即可。

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

mapper.xml

<select id="checkExist" resultType="Integer">
        select 1 from t_sys_user where username = #{name} limit 1
    </select>

dao接口

public interface UserDao  extends Mapper<User> {
    Integer checkExist(@Param("name") String name);
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {
    @Resource
    private UserDao userDao;
    @Test
    public void test() {
        String name = "zhangsan1";
        Integer exist = userDao.checkExist(name);
        if (null != exist) {
            System.out.println("存在");
        } else {
            System.out.println("不存在");
        }
    }
}
原文地址:https://www.cnblogs.com/zwh0910/p/15557061.html