Mysql SQL中的IF有些奇怪

Mysql SQL中的IF有些奇怪,mysql,sql,Mysql,Sql,我有一个更新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 no

我有一个更新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;
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;
它不影响返回的值: 匹配0行受影响的行:1已更改:0警告:0 而且圣母玛利亚记录不会更新

但是,当我使用如下所示:

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;
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更新!,但我不知道为什么… 任何人都能找出这两种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
 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 JOIN
st.deleted
可以
NULL
,因此条件
如果(st.deleted=0)
也会导致
NULL
,左连接右侧表上的条件应该放在
on
子句中
然后,您可以假设当满足
st.id不为null
时,
st_deleted=0
也是真的,所以您只需要检查第一个条件。

对于以后搜索的人,请澄清这是微软ehh还是微软ehh,我检查mysql数据库,st.deleted是0。@yunji它可以是
NULL
,因为
左连接
,而不是实际的
NULL
值。在发布评论之前是否运行了我的查询??