where 1=1; 這個條件始終為True,在不定數量查詢條件情況下,1=1可以很方便的規范語句。
例如為不定數量的查詢條件,我們在后台寫查詢的時候,類似於這樣的語句 string sql ="select * from table where"
if(starttime!=null){
sql =sql+" starttime="+starttime
}
if(endtime !=null){
sql =sql+"and endtime ="+endtime
}
這時我們的查詢語句就是 select * from table where starttime =2015-04-05 and endtime = 2015-04-07,查詢語句正確
但是如果條件都不滿足的話,語句就變成了 select * from table where ,這時候查詢就會報錯,
加上1=1的時候
string sql ="select * from table where 1=1",
if(starttime!=null){
sql =sql+" and starttime="+starttime
}
if(endtime !=null){
sql =sql+"and endtime ="+endtime
}
當兩個條件成立的時候 select * from table where 1=1 and starttime =2015-04-05 and endtime = 2015-04-07, 語句正確
當兩個條件不滿足時 select * from table where 1=1 ,語句正確,會返回table表的所有數據