简体   繁体   English

使用第一个表中的值一次更新两个表

[英]Update two tables at once, using values from first table

So I need to Update table scores and use the updated value of column won to update the second table tbl_users . 所以,我需要更新表scores ,并使用更新后的值的列won更新第二个表tbl_users So far the code updates scores , but uses the old value of won for the second table update: 到目前为止,代码更新了scores ,但是使用了won的旧值来进行第二次表更新:

UPDATE scores a
left join tbl_users b on
    a.uid = b.userID
SET a.won = CASE  
WHEN a.nright = '0' THEN '0' 
WHEN a.nright = '1' THEN '25' 
WHEN a.nright = '2' THEN '50' 
WHEN a.nright = '3' THEN '100' 
WHEN a.nright = '4' THEN '200' 
WHEN a.nright = '5' THEN '400' 
WHEN a.nright = '6' THEN '700' 
WHEN a.nright = '7' THEN '1000' 
END,
b.pts=b.pts+a.won, 
b.pts_total=b.pts_total+a.won
WHERE a.uid=$user AND b.userID=$user

What you want to do is explicitly documented as correct: 您要做的事情已明确记录为正确的:

The second assignment in the following statement sets col2 to the current (updated) col1 value, not the original col1 value. 以下语句中的第二个赋值将col2设置为当前(更新)的col1值,而不是原始的col1值。 The result is that col1 and col2 have the same value. 结果是col1和col2具有相同的值。 This behavior differs from standard SQL. 此行为不同于标准SQL。

 UPDATE t1 SET col1 = col1 + 1, col2 = col1; 

I assume that the issue is the multi-table update, where the set pulls the value from the earlier table. 我认为问题是多表更新,其中set从较早的表中提取值。

You may be able to fix this using variables. 您也许可以使用变量来解决此问题。 I am not 100% sure, but the following is worth a try: 我不确定100%,但是值得尝试以下方法:

UPDATE scores s JOIN
       tbl_users u 
       ON s.uid = .uuserID
    SET s.won = (@w := (CASE  WHEN s.nright = '0' THEN '0' 
                              WHEN s.nright = '1' THEN '25' 
                              WHEN s.nright = '2' THEN '50' 
                              WHEN s.nright = '3' THEN '100' 
                              WHEN s.nright = '4' THEN '200' 
                              WHEN s.nright = '5' THEN '400' 
                              WHEN s.nright = '6' THEN '700' 
                              WHEN s.nright = '7' THEN '1000' 
                       END)
                ),
       u.pts = u.pts + @w, 
       u.pts_total = u.pts_total + @w
    WHERE s.uid = $user ;

The documentation strongly suggests that the set clauses are processed in order for a single table. 该文档强烈建议为单个表顺序处理set子句。 Alas, it is not clear whether this is always true for multiple tables. las,目前尚不清楚对于多个表是否总是如此。

If not, you can use two updates. 如果没有,则可以使用两个更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM