SQL judges whether "exists", is it still count operation

According to a certain condition, query "Yes" and "No" from the database table, there are only two states, so why do you still have to select count(*)/select count(1) when writing SQL?

Most people’s writing

When reviewing the code many times, I found the following phenomenon:

In the business code, you need to query whether there are records based on one or more conditions, and don't care how many records there are. Common SQL and code writing are as follows

sql is written as follows

SELECT count(*) FROM table WHERE a = 1 AND b = 2  

Java writing:

int nums = xxDao.countXxxxByXxx(params);  
if ( nums > 0 ) {   
//当存在时,执行这里的代码  
}   
else {   
//当不存在时,执行这里的代码  
}  

Does it feel perfect BUT

Optimize operation

sql is written as follows

SELECT 1 FROM table WHERE a = 1 AND b = 2 LIMIT 1 

Java writing:

Integer exist = xxDao.existXxxxByXxx(params);  
if ( exist != NULL ) {  
  //当存在时,执行这里的代码  
} else {  
  //当不存在时,执行这里的代码  
}  

SQL is no longer used count, but used instead LIMIT 1(mysql), so that when the database query encounters one, it will return, don't continue to find how many more ones are left

Just judge whether it is not empty in the business code

to sum up:

Simple and practical, performance improved

Guess you like

Origin blog.csdn.net/qq_42464423/article/details/109259563
Recommended