select * from table1 where 1=1与select * from table1彻底没有区别,甚至还有其余许多写法,1<>2,'a'='a','a'<>'b',其目的就只有一个,where 的条件为永真,获得的结果就是未加约束条件的。sql
在SQL注入时会用到这个,例如select * from table1 where name='lala'给强行加上select * from table1 where name='lala' or 1=1这就又变成了无约束的查询了。spa
最近发现的妙用在于,在不定数量查询条件状况下,1=1能够很方便的规范语句。例如一个查询可能有name,age,height,weight约束,也可能没有,那该如何处理呢?code
String sql=select * from table1 where 1=1it
为何要写多余的1=1?立刻就知道了。table
if(!name.equals("")){
sql=sql+"name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"weight='"+weight+"'";
}
若是不写1=1呢,那么在每个不为空的查询条件面前,都必须判断有没有where字句,不然要在第一个出现的地方加where
where 1=1的写法是为了检化程序中对条件的检测
打个比方有三个参数a, b, c
@sql=select * from tb'
这三个参数均可能为空
这时你要构造语句的话,一个个检测再写语句就麻烦
好比
if @a is not null
@sql=@sql + " where a=' + @a
if @b is not null
这里你怎么写?要不要加where 或直接用 and ?,你这里还要对@a是否为空进行检测class
用上 where 1=1 以后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 orselect
拷贝表
create table_name as select * from Source_table where 1=1;程序
复制表结构
create table_name as select * from Source_table where 1 <> 1;demo