SQL judges whether "exists", is still using count operation?

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

Whether it is a new star programmer or a veteran programmer who has been on the battlefield for many years, they are always count.

Most people’s way of writing

When reviewing the code several times, the following phenomena were found:

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

SQL writing:

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

Java writing:

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

Does it feel OK? No problem

Optimization

The recommended writing is as follows:

SQL writing:

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, so that when the database query encounters one, it will return, and don't continue to find how many more ones are left

You can directly judge whether it is not empty in the business code

to sum up

The more items found according to the query conditions, the more obvious the performance improvement, and in some cases, the creation of joint indexes can be reduced.

Source: https://urlify.cn/JjYBJn

Guess you like

Origin blog.csdn.net/u012660464/article/details/108805648
Recommended