SQL中“where 1=1”的用法

发布时间:2021-01-15 11:07:33 作者:小新
来源:亿速云 阅读:283

这篇文章给大家分享的是有关SQL中“where 1=1”的用法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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);
    }

感谢各位的阅读!关于“SQL中“where 1=1”的用法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. delphi中try的用法1
  2. mysql中为什么要用where 1=1

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

sql where

上一篇:sql server 2008安装重新启动计算机失败的解决

下一篇:在access数据库中实体如何表示

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》