我想一次更新两个表。下面的代码似乎工作正常。但是,在某些情况下,bidGroups中没有条目,这意味着整个语句将失败。如何调整它以便更新第一位(watchedItems)并且如果watchedItems.bidGroupID IS NULL则不尝试第二部分
UPDATE watchedItems, bidGroups
SET watchedItems.won=1, bidGroups.bidGroupQty=bidGroups.bidGroupQty-1
WHERE watchedItems.id=2
AND watchedItems.aid=200618152822
AND bidGroups.bidGroupID=watchedItems.bidGroupID
AND bidGroups.id=2;
我试过这个,但语法错了..
UPDATE watchedItems, bidGroups
SET watchedItems.won=1,
CASE WHEN watchedItems.bidGroupID IS NOT NULL THEN bidGroups.bidGroupQty=bidGroups.bidGroupQty-1
ELSE END
WHERE watchedItems.id=2
AND watchedItems.aid=200618152822
AND bidGroups.bidGroupID=watchedItems.bidGroupID
AND bidGroups.id=2
答案 0 :(得分:2)
你需要做left outer join
全部。
update watchedItems wi left outer join bidGroups bg
on wi.bidGroupID = bg.bidGroupID
set
wi.won = 1,
bg.bidGroupQty = bg.bidGroupQty - 1
where wi.id = 2
and wi.aid = 200618152822
and (bg.id = 2 or bg.id is null)
如果watchedItems.bidGroupId
为空,那么它只会更新watchedItems
中找到的行,因为bidGroups
中无法加入任何内容。如果不是,并且连接在两个表中都获得了行,则对两个表的更新都会发生。
仅使用watchedItems, bidGroups
与inner join
相同,因此当bidGroups
中没有要加入的条目时,您也无法从{{1}获得结果}}。在watchedItems
而不是join
上使用相同的where
和select
条款,您会发现不同之处:
update
VS
select wi.won, bg.bidGroupQty
from watchedItems wi, bidGroups bg
where wi.id = 2 and wi.aid = 200618152822
and (bg.id = 2 or bg.id is null)
and wi.bidGroupID = bg.bidGroupID
答案 1 :(得分:2)
以这种方式尝试LEFT JOIN:
UPDATE watchedItems
LEFT JOIN bidGroups ON watchedItems.bidGroupID = bidGroups.bidGroupID AND bidGroups.id=2
SET watchedItems.won=1, bidGroups.bidGroupQty=bidGroups.bidGroupQty-1
WHERE watchedItems.id=2
AND watchedItems.aid=200618152822;
...
答案 2 :(得分:1)
如果您不想更改,只需将其设置为当前值即可。 并且MySQL通常在值相同时不更新它来优化它。
UPDATE watchedItems
LEFT JOIN bidGroups ON bidGroups.bidGroupID=watchedItems.bidGroupID
AND bidGroups.id=2
SET watchedItems.won=1,
bidGroups.bidGroupQty= if(watchedItems.bidGroupID IS NULL,
bidGroups.bidGroupQty,
bidGroups.bidGroupQty-1)
WHERE watchedItems.id=2
AND watchedItems.aid=200618152822;
但是,您不需要if
,因为如果watchedItems.bidGroupID IS NULL
,则不会加入bidGroups中的行,并且会忽略该不存在的行的更新。
所以bidGroups.bidGroupQty=bidGroups.bidGroupQty-1
很好