轉(zhuǎn)!sql中where 1=1 的使用

在mysql中,where 1=1; 這個(gè)條件始終為True,在不定數(shù)量查詢條件情況下,1=1可以很方便的規(guī)范語句。
image

例如為不定數(shù)量的查詢條件,我們?cè)诤笈_(tái)寫查詢的時(shí)候,類似于這樣的語句

$sql = "select * from table where";

當(dāng)條件starttime和endtime都為空時(shí)

if(starttime!=null){
    $sql = $sql+" starttime="+$starttime;
} 
if(endtime !=null){
    $sql = $sql+"and endtime ="+$endtime;
}

這時(shí)我們的查詢語句就是 select * from table where starttime =2015-04-05 and endtime = 2015-04-07,查詢語句正確

但是如果條件都不滿足的話,語句就變成了 select * from table where ,這時(shí)候查詢就會(huì)報(bào)錯(cuò),
加上1=1的時(shí)候

 $sql ="select * from table where 1=1",
if(starttime!=null){
    $sql = $sql+" and  starttime="+$starttime;
} 
if($endtime !=null){
    $sql = $sql+"and endtime ="+$endtime;
}

當(dāng)兩個(gè)條件成立的時(shí)候 select * from table where 1=1 and starttime =2015-04-05 and endtime = 2015-04-07, 語句正確

當(dāng)兩個(gè)條件不滿足時(shí) select * from table where 1=1 ,語句正確,會(huì)返回table表的所有數(shù)據(jù)

原文鏈接:
https://www.cnblogs.com/wangcongsuibi/p/7813445.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容