SQL multi-condition query where 1=1

To achieve this dynamic SQL statement assembly, we can create a string in the host language, and then add SQL statement fragments to the string by judging whether each checkbox is checked one by one. There is a problem here that the SQL statement contains a WHERE clause when a check box is checked, and there is no WHERE clause when all check boxes are not checked, so add each filter condition When judging, it is necessary to judge whether there is already a WHERE statement. If there is no WHERE statement, add a WHERE statement. It is necessary to judge when each checkbox is judged, which makes it very troublesome to use, "smart programmers are lazy programmers", so the developers thought of a shortcut: specify a SQL statement that is always true The conditional statement (such as "1=1"), so that there is no need to consider the existence of the WHERE statement. The pseudo code is as follows:

String sql = " SELECT * FROM T_Employee WHERE 1=1";
if (job number checkbox checked)
{
sql.appendLine("AND FNumber BETWEEN '"+the content of the work number text box 1+"' AND '"+the content of the work number text box 2+"'");
}
if(name checkbox checked)
{
sql.appendLine("AND FName LIKE '%"+Name text box content+"%'");
}
if (age checkbox checked)
{
sql.appendLine("AND Fage BETWEEN "+ age text box 1 content + " AND "+ age text box 2 content);
}
executeSQL(sql);
In this way, if the checkbox before name and age is not selected, the following SQL statement will be executed:
SELECT * FROM T_Employee WHERE 1=1
AND FNumber BETWEEN 'DEV001' AND 'DEV008'
AND FSalary BETWEEN 3000 AND 6000
And if all the checkboxes are unchecked, the following SQL statement will be executed:
SELECT * FROM T_Employee WHERE 1=1



This seems to solve the problem very beautifully, but I don’t know that this may cause a very large performance loss, because the database system cannot use query optimization strategies such as indexes after the filter condition of “1=1” is added, and the database system will Forced to scan each row of data (that is, full table scan) to compare whether the row satisfies the filter conditions, the query speed will be very slow when the amount of data in the table is relatively large. Therefore, if data retrieval has high performance requirements, do not use this "easy" method. A reference implementation is given below, and the pseudo code is as follows:


StringBuilder buff = new StringBuilder("select * from T ")
String sp = " WHERE ";
foreach() {
if (...) {
buff.append(sp).append(cond);
sp = " AND ";
}
}


But is where 1=1 really inefficient? The answer is no effect.

   Because the query analyzer directly filters out 1=1 in the algebraic tree optimization stage. This feature is what is known as "Constant Folding" in the query optimizer.

For in-depth understanding, see: https://www.cnblogs.com/CareySon/p/4138575.htm



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324524289&siteId=291194637