where 1=1;有什么用?在SQL语言中,这个条件始终为True,写这一句话就跟没写一样。select * from table where 1=1与select * from table完全没有区别,其目的就是使 where 的条件永远为true,得到的结果就是未加约束条件的结果。
在查询条件数量不确定的条件情况下,使用 where 1=1可以很方便的规范语句。例如一个查询中可能有name,age,height,weight等不确定数量的约束条件,那么使用
String sql="select * from table where 1=1";
if(!name.equals("")){
sql=sql+"and/or name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"and/or age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"and/or height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"and/or weight='"+weight+"'";
}
如果不写1=1,那么在每一个不为空的查询条件面前,都必须判断有没有where字句,哪里该加where,哪里该加and/or
用上 where 1=1 之后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 or
完全复制表
create table_name as select * from Source_table where 1=1;
复制表结构
create table_name as select * from Source_table where 1=0;
---------------------
作者:xcliang9418
来源:优快云
原文:https://blog.youkuaiyun.com/xcliang9418/article/details/79146114
版权声明:本文为博主原创文章,转载请附上博文链接!