sql語句中where 1=1的作用
where 1=1
最近看到很多sql裡用到where 1=1,原來覺得這沒用嘛,但是又想到如果沒用為什麼要寫呢?於是在網上
查了查,在這裡就淺談一下:
1=1 永真, 1<>1 永假。
1<>1 的用處:
用於只取結構不取資料的場合
例如:
create table table_temp tablespace tbs_temp as
select * from table_ori where 1<>1
建成一個與table_ori 結構相同的表table_temp,但是不要table_ori 裡的資料。(除了表結構,其它結
構也同理)
1=1的用處
用於動態SQL
例如 lv_string := 'select tbl_name,tbl_desc from tbl_test where 1=1 '||l_condition;
當用戶選擇了查詢的名稱'abc'時l_condition :='and tbl_name = ''abc'''';但是當用戶沒有
選擇名稱查詢時l_condition就為空 這樣 lv_string = 'select tbl_name,tbl_desc from tbl_test
where 1=1 ' ,執行也不會出錯,相當於沒有限制名稱條件。但是如果沒有1=1的條件,則lv_string =
'select tbl_name,tbl_desc from tbl_test where ';這樣就會報錯。
除了1=1 或1<>1之外的其它永真永假的條件同理。
----------------------------------------------
where 1=1;有什麼用?在SQL語言中,這個條件始終為True,寫這一句話就跟沒寫一樣。select * from table where 1=1與select * from table完全沒有區別,其目的就是使 where 的條件永遠為true,得到的結果就是未加約束條件的結果。
在查詢條件數量不確定的條件情況下,使用 where 1=1可以很方便的規範語句。例如一個查詢中可能有name,age,height,weight等不確定數量的約束條件,那麼使用
String sql="select * from table where 1=1";
if(!name.equals("")){
sql=sql+"and/or name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"and/or age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"and/or height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"and/or weight='"+weight+"'";
}
如果不寫1=1,那麼在每一個不為空的查詢條件面前,都必須判斷有沒有where字句,哪裡該加where,哪裡該加and/or
用上 where 1=1 之後,就不存在這樣的問題, 條件是 and 就直接and ,是or就直接接 or
完全複製表
create table_name as select * from Source_table where 1=1;
複製表結構
create table_name as select * from Source_table where 1=0;