即使表b中没有行,MySql也会在表a中连接更新行

时间:2014-09-11 13:45:51

标签: mysql sql

更新两个表中的行时要使用的连接是什么,即使表b中没有行,也会更新tablea中的行?

这是我失败的原因:

update
  items_mod a
  left join item_images b on a.itemHandle = b.imgHandle
set
  a.itemPubStatus = 0,
  a.itemStatusSet = 1,
  a.itemAdminMessage = 'Test',
  b.imgStatus = 1,
  b.imgPublished = 1 
where
  a.itemId = 2 
  and a.itemPubStatus = 2
  and a.itemPrePub = 1
  and b.imgStatus = 0
  and b.imgDeleted = 0;

item_images中有行,但没有符合b.imgStatus = 0 and b.imgDeleted = 0

这两个条件的行

如何对sql进行编码,以便即使item_mod中没有更新内容,sql也会更新item_images

2 个答案:

答案 0 :(得分:1)

地点

and b.imgStatus = 0
  and b.imgDeleted = 0
在左连接子句中

并从where中删除它们。在连接之后测试的位置,并且因为b将全部为空,无法找到任何匹配。

答案 1 :(得分:0)

"外在" WHERE子句中的这两个谓词否定了LEFT JOIN操作;

b.imgStatus = 0 and b.imgDeleted = 0

那些有效地过滤掉任何具有NULL值的行,因此查询等同于INNER连接。

使这个"外部" join,您可以将这两个谓词重定位到ON子句。例如:

UPDATE items_mod a
  LEFT
  JOIN item_images b
    ON b.imgHandle = a.itemHandle
   AND b.imgStatus = 0 
   AND b.imgDeleted = 0
   SET a.itemPubStatus = 0
     , a.itemStatusSet = 1
     , a.itemAdminMessage = 'Test'
     , b.imgStatus = 1
     , b.imgPublished = 1 
 WHERE a.itemId = 2
   AND a.itemPubStatus = 2 
   AND a.itemPrePub = 1