共計 1519 個字符,預計需要花費 4 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
這篇文章給大家分享的是有關 SQL 中“where 1=1”的用法的內容。丸趣 TV 小編覺得挺實用的,因此分享給大家做個參考,一起跟隨丸趣 TV 小編過來看看吧。
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”的用法”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
向 AI 問一下細節