侧边栏壁纸
博主头像
一个九零后的萤火虫博主等级

行动起来,活在当下

  • 累计撰写 33 篇文章
  • 累计创建 7 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SQL 语句中 where 条件后 写上1=1,这是为什么?

Administrator
2024-01-25 / 0 评论 / 0 点赞 / 9 阅读 / 1088 字

    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;

0

评论区