where 1=1有什么用?在sql语言中,写这么一句话就跟没写一样。
select * from table1 where 1=1与select * from table1完全没有区别,甚至还有其他许多写法,1<>2,'a'='a','a'<>'b',其目的就只有一个,where 的条件为永真,得到的结果就是未加约束条件的。
在sql注入时会用到这个,例如select * from table1 where name='lala'给强行加上select * from table1 where name='lala' or 1=1这就又变成了无约束的查询了。
最近发现的妙用在于,在不定数量查询条件情况下,1=1可以很方便的规范语句。例如一个查询可能有name,age,height,weight约束,也可能没有,那该如何处理呢?
string sql=select * from table1 where 1=1
为什么要写多余的1=1?马上就知道了。
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是否为空进行检测
用上 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 <> 1;
如对本文有疑问, 点击进行留言回复!!
JDBC访问数据库操作详解(四)之三层架构:以MySQL为例
MySQL 三万字精华总结 + 面试100 问,和面试官扯皮,吹牛逼!绰绰有余(一:MySql架构,数据类型,存储引擎)收藏系列!
服务器Centos部署MySql并连接Navicat过程详解
网友评论