您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

SQL中“where 1=1”有什么用?

2024/4/12 6:28:29发布26次查看
sql中where 1=1的用处
解释:
其实,1=1 是永恒成立的,意思无条件的,也就是说在sql语句中有没有这个1=1都可以。
这个1=1常用于应用程序根据用户选择项的不同拼凑where条件时用的。
如:web界面查询用户的信息,where默认为1=1,这样用户即使不选择任何条件,sql查询也不会出错。如果用户选择了姓名,那么where变成了where 1=1 and 姓名=‘用户输入的姓名’,如果还选择了其他的条件,就不断在where 条件后追加 and语句就行了。
如果不用1=1的话,每加一个条件,都要判断前面有没有where 条件,如果没有就写where …,有就写and语句,因此此时用1=1可以简化了应用程序的复杂度。
例:
如下面代码首先定义$where= ‘1=1’,后面就可以不用去判断是否存在$where
public function listaction()    {       $get = $this->getquery();        $statementbalancedetailmodel = m('ticket\statementbalancedetail');        $page = isset($get['page']) ? intval($get['page']) : 1;        $pagesize = isset($get['page_size']) ? intval($get['page_size']) : 10;        //用处        $where = ' 1=1 ';        $binds = array();        if (isset($get['id']) && $get['id'] != '') {            $where .= ' and id = :id';            $binds['id'] = trim($get['id']);        }        if (isset($get['shop_name']) && $get['shop_name'] != '') {            $where .= ' and shop_name = :shop_name';            $binds['shop_name'] = trim($get['shop_name']);        }        if (isset($get['statement_sn']) && $get['statement_sn'] != '') {            $where .= ' and statement_sn = :statement_sn';            $binds['statement_sn'] = trim($get['statement_sn']);        }        $where .= ' order by id desc';        $result = $statementbalancedetailmodel->paginate($where, $pagesize, $page, $fields = array(), $binds);        $scenerylist = $result['data'];        $total = $result['total_result'];        $pager = paginate::web($total, $page, $pagesize);        $data = array(            'pager' => $pager,            'scenerylist' => $scenerylist,        );        $this->getview()->assign($data);    }
本文转载自:https://blog.csdn.net/longgeaisisi/article/details/100599010
推荐学习:mysql教程
以上就是sql中“where 1=1”有什么用?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product