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('TicketStatementBalanceDetail');
$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);
}
1、本站目前拥有近 1000+ 精品收费资源,现在加入VIP会员即可全部下载。
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
欧迪资源网 » SQL中“where 1=1”有什么用?
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
欧迪资源网 » SQL中“where 1=1”有什么用?

发表评论