您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)SQL中“where 1=1”的用法的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
SQL中where 1=1的用處
解釋?zhuān)?/strong>
其實(shí),1=1 是永恒成立的,意思無(wú)條件的,也就是說(shuō)在SQL語(yǔ)句中有沒(méi)有這個(gè)1=1都可以。
這個(gè)1=1常用于應(yīng)用程序根據(jù)用戶(hù)選擇項(xiàng)的不同拼湊where條件時(shí)用的。
如:web界面查詢(xún)用戶(hù)的信息,where默認(rèn)為1=1,這樣用戶(hù)即使不選擇任何條件,sql查詢(xún)也不會(huì)出錯(cuò)。如果用戶(hù)選擇了姓名,那么where變成了where 1=1 and 姓名=‘用戶(hù)輸入的姓名’,如果還選擇了其他的條件,就不斷在where 條件后追加 and語(yǔ)句就行了。
如果不用1=1的話(huà),每加一個(gè)條件,都要判斷前面有沒(méi)有where 條件,如果沒(méi)有就寫(xiě)where …,有就寫(xiě)and語(yǔ)句,因此此時(shí)用1=1可以簡(jiǎn)化了應(yīng)用程序的復(fù)雜度。
例:
如下面代碼首先定義$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); }
感謝各位的閱讀!關(guān)于“SQL中“where 1=1”的用法”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。