程序员在编程过程中,经常会在代码中使用到“where 1=1”,这是为什么呢?
这段代码应该是由程序(例如Java)中生成的,where条件中 1=1 之后的条件是通过 if 块动态变化的。
例 如
String sql="select * from table_name where 1=1";
if( conditon 1) {
sql=sql+" and var2=value2";
if(conditon 2) {
sql=sql+" and var3=value3";
where 1=1 是为了避免where 关键字后面的第一个词直接就是 “and”而导致语法错误。
动态SQL中连接AND条件
where 1=1 是为了避免where 关键字后面的第一个词直接就是 “and”而导致语法错误。
where后面总要有语句,加上了1=1后就可以保证语法不会出错!
select * from table where 1=1
因为table中根本就没有名称为1的字段,所以该SQL等效于select * from table,这个SQL语句很明显是全表扫描,需要大量的IO操作,数据量越大越慢,建议查询时增加必输项,即where 1=1后面追加一些常用的必选条件,并且将这些必选条件建立适当的索引,效率会大大提高
拷贝表
create table table_name as select * from Source_table where 1=1;
复制表结构
create table table_name as select * from Source_table where 1 <> 1;
所以在查询时,where1=1的后面需要增加其它条件,并且给这些条件建立适当的索引,效率就会大大提高。
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.