而对于开发者,如果检索条件不确定,即根据用户的画面输入追加检索条件时,这的“where 1=1”就非常有用。
往简单说,它可以简化程序,免去繁琐的判断,提高程序效率。往复杂说呢,可以减轻程序员的开发负担,最大限度的提高工作效率。
上例子:①使用1=1
String sql =Select A.x,A.Y FROM table A Where 1=1;
StringBuffer sqlBuffer = new StringBuffer ;
sqlBuffer.append(sql);
如果画面有三个独立的可选输入项目l,m.n
if ( l != null ) {
sqlBuffer.append("and A.l = l");
}
if ( m != null ) {
sqlBuffer.append("and A.m = m");
}
if ( n != null ) {
sqlBuffer.append("and A.n= n");
}
这个是使用了“1=1”的用法,直接判断追加就行。
String sql =Select A.x,A.Y FROM table A ;
StringBuffer sqlBuffer = new StringBuffer ;
sqlBuffer.append(sql);
if (l != 空) {
sqlBuffer.append("where A.l = l");
} else {
if (m != 空) {
sqlBuffer.append("where A.m = m");
} else {
if (n != 空)
sqlBuffer.append("where A.n = n");
}
}
if (l != 空 and m != 空) {
sqlBuffer.append(" and A.m = m");
}else if (l != 空 and m != 空 and n != 空) {
sqlBuffer.append(" and A.n = n");
}
每一个项目的追加都要判断前面的检索条件是否存在,以确定是否要“where”。
有了上面的比较1=1的优势就比较明显了。