where 1=1有什么用?在SQL語(yǔ)言中,寫(xiě)這么一句話(huà)就跟沒(méi)寫(xiě)一樣。
select * from table1 where 1=1與select * from table1完全沒(méi)有區(qū)別,甚至還有其他許多寫(xiě)法,1<>2,'a'='a','a'<>'b',其目的就只有一個(gè),where 的條件為永真,得到的結(jié)果就是未加約束條件的。
在SQL注入時(shí)會(huì)用到這個(gè),例如select * from table1 where name='lala'給強(qiáng)行加上select * from table1 where name='lala' or 1=1這就又變成了無(wú)約束的查詢(xún)了。
最近發(fā)現(xiàn)的妙用在于,在不定數(shù)量查詢(xún)條件情況下,1=1可以很方便的規(guī)范語(yǔ)句。例如一個(gè)查詢(xún)可能有name,age,height,weight約束,也可能沒(méi)有,那該如何處理呢?
String sql=select * from table1 where 1=1
為什么要寫(xiě)多余的1=1?馬上就知道了。
where 1=1的寫(xiě)法是為了檢化程序中對(duì)條件的檢測(cè)
打個(gè)比方有三個(gè)參數(shù)a, b, c
@sql=select * from tb'
這三個(gè)參數(shù)都可能為空
這時(shí)你要構(gòu)造語(yǔ)句的話(huà),一個(gè)個(gè)檢測(cè)再寫(xiě)語(yǔ)句就麻煩
比如
if @a is not null
@sql=@sql + " where a=' + @a
if @b is not null
這里你怎么寫(xiě)?要不要加where 或直接用 and ?,你這里還要對(duì)@a是否為空進(jìn)行檢測(cè)
用上 where 1=1 之后,就不存在這樣的問(wèn)題, 條件是 and 就直接and ,是or就直接接 or
拷貝表
create table_name as select * from Source_table where 1=1;
復(fù)制表結(jié)構(gòu)
create table_name as select * from Source_table where 1 <> 1;
新聞熱點(diǎn)
疑難解答
圖片精選