SQL statement after the condition where 1 = 1 is written on what it means!

Source: San

cloud.tencent.com/developer/article/1475146

Yes, Xiao Bian blowing a cow, is this small series do not look at the tutorial will own to where 1 = 1 in the native sql plus years, and wrote the bulk insert sql assembled students should be more clear, automatic splicing

Of course, Xiao Bian also not a lot of, we need to learn and progress together

This code should be by a program (e.g., Java) generated, where conditions after condition 1 = 1 if the block is by dynamic change. E.g:

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 is to avoid the first word directly behind where the keyword is "and" caused a syntax error.

Dynamic SQL connection AND condition

where 1 = 1 is to avoid the first word directly behind where the keyword is "and" caused a syntax error.

Where there must be a statement later, added after 1 = 1 can not go wrong syntax guarantee!

select * from table where 1=1

Because the table is simply not the name for the field 1, it is equivalent to the SQL select * from table,

The SQL statement is obviously full table scan, requires a lot of IO operation, the greater the amount of data to slower,

Proposal to increase the query losing items, that is, where 1 = 1 appends some common mandatory conditions and establish appropriate index these mandatory conditions will greatly improve efficiency

Copy table

create table table_name  as  select  *  from  Source_table  where  1=1;

Copy Table Structure

create table table_name  as  select  *  from  Source_table  where  1 <> 1;

Published 25 original articles · won praise 1 · views 9701

Guess you like

Origin blog.csdn.net/weixin_45727359/article/details/104666973