SQL中“where 1=1”的用法

这篇文章给大家分享的是有关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”的用法”这篇文章分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

相关文章

这篇文章主要介绍“hive和mysql的区别是什么”,在日常操作中...
这篇“MySQL数据库如何改名”文章的知识点大部分人都不太理解...
这篇文章主要介绍“mysql版本查询命令是什么”的相关知识,小...
本篇内容介绍了“mysql怎么修改字段的内容”的有关知识,在实...
这篇文章主要讲解了“mysql怎么删除unique约束”,文中的讲解...
今天小编给大家分享一下mysql怎么查询不为空的字段的相关知识...