转!sql中where 1=1 的使用

在mysql中,where 1=1; 这个条件始终为True,在不定数量查询条件情况下,1=1可以很方便的规范语句。
image

例如为不定数量的查询条件,我们在后台写查询的时候,类似于这样的语句

$sql = "select * from table where";

当条件starttime和endtime都为空时

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的时候

 $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表的所有数据

原文链接:
https://www.cnblogs.com/wangcongsuibi/p/7813445.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容