当前位置:Gxlcms > 数据库问题 > SQL语句中为什么要用 where 1=1

SQL语句中为什么要用 where 1=1

时间:2021-07-01 10:21:17 帮助过:11人阅读

1=1 是永恒成立的,意思无条件的,也就是说在SQL语句中有没有这个1=1都可以。

如:web界面查询用户的信息,where默认为1=1,这样用户即使不选择任何条件,sql查询也不会出错。如果用户选择了姓名,那么where变成了where 1=1 and 姓名=‘用户输入的姓名‘,如果还选择了其他的条件,就不断在where 条件后追加 and语句就行了。

如果不用1=1的话,每加一个条件,都要判断前面有没有where 条件,如果没有就写where ...,有就写and语句,因此此时用1=1可以简化了应用程序的复杂度。

例如为不定数量的查询条件,我们在后台写查询的时候,类似于这样的语句 string sql ="select * from table where"

if(starttime!=null){

sql =sql+" starttime="+starttime

if(endtime !=null){

sql =sql+"and endtime ="+endtime

}

这时我们的查询语句就是 select * from table where starttime =2015-04-05 and endtime = 2015-04-07,查询语句正确

但是如果条件都不满足的话,语句就变成了 select * from table where ,这时候查询就会报错,

加上1=1的时候

string sql ="select * from table where 1=1",

if(starttime!=null){

sql =sql+" and  starttime="+starttime

if(endtime !=null){

sql =sql+"and endtime ="+endtime

}

当两个条件成立的时候 select * from table where 1=1 and starttime =2015-04-05 and endtime = 2015-04-07, 语句正确

当两个条件不满足时 select * from table where 1=1 ,语句正确,会返回table表的所有数据

SQL语句中为什么要用 where 1=1

标签:简化   应用程序   art   因此   tar   bsp   span   ber   sql   

人气教程排行