2016-11-09 91 views
1

我哈瓦一個更新SQL象下面這樣:奇怪的事情與IF在SQL

update saletargets_import_data as st_im left join saletargets as st 
on st_im.saletarget_hospital_id=st.saletarget_hospital_id 
and st_im.saletarget_product_id=st.saletarget_product_id 
set st_im.record_id=if(st.deleted=0 and st.id is not null,st.id,st_im.record_id) 
where st_im.import_id=383; 

它不affect.which回報: 0行(S)受影響的行匹配:1:0的警告:0 和st_im.record_id不更新

然而

,當我使用如下:

update saletargets_import_data as st_im left join saletargets as st 
on st_im.saletarget_hospital_id=st.saletarget_hospital_id 
and st_im.saletarget_product_id=st.saletarget_product_id 
set st_im.record_id=if(st.id is not null,st.id,st_im.record_id) 
where st_im.import_id=383 and st.deleted=0; 

它的工作原理,在st_im.record_id更新!但我不知道爲什麼... Clould任何人都可以看出這兩個SQL之間的區別嗎?

+0

對於未來搜索的人,請澄清一下,如果是[tag:mysql]或者微軟[tag:sql-server] – mendosi

回答

1

試試這個:

update saletargets_import_data as st_im 
left join saletargets as st 
    on st_im.saletarget_hospital_id = st.saletarget_hospital_id 
and st_im.saletarget_product_id = st.saletarget_product_id 
and st.deleted = 0 
    set st_im.record_id = if(st.id is not null, st.id, st_im.record_id) 
where st_im.import_id = 383 

的問題是LEFT JOINst.deleted可以NULL,所以條件if(st.deleted = 0)將導致NULL還有,在左的右表條件加入應內放置ON條款。
然後,你可以假設當st.id is not null被滿足時,st_deleted = 0也是如此,所以你只需要檢查第一個條件。

+0

呃,我檢查mysql數據庫,st.deleted是0. – yunji

+0

@yunji它可以由於「LEFT JOIN」而不是「NULL」值。發表評論之前,您是否運行了我的查詢? – sagi