使用ORDER BY和LIMIT MYSQL更新多个不同的表

时间:2018-06-17 15:54:58

标签: mysql sql-update sql-order-by limit

对于初学者我知道这是不可能的,我必须以某种方式选择,但我不知道该怎么做。这是我现在简化的查询。

UPDATE table1 AS tb1 
LEFT JOIN table2 AS tb2 ON (tb1.id = tb2.id AND tb1.column1 = tb2.column1)
SET
tb1.columX = (@position_temp := @position_temp+1),
tb1.columY = 2,
tb1.columZ = 3,
tb2.columA = 0
WHERE tb1.id = X AND tb1.columnB = 10
ORDER BY tb1.columX DESC
LIMIT 10;

1 个答案:

答案 0 :(得分:0)

您无法在ORDER BY中使用UPDATE并在MySQL中使用JOIN。假设table1(id)和`table2(id,column1)是唯一的,这应该有效:

UPDATE table1 t1 JOIN
       (SELECT tt1.*, tt2.column1
        FROM table1 tt1 LEFT JOIN
             table2 tt2
             ON tt1.id = tt2.id AND tt1.column1 = tt2.column1
        WHERE tt1.id = X AND tt1.columnB = 10
        ORDER BY tt1.columX DESC
        LIMIT 10
       ) tt1
       ON tt1.id = t1.id LEFT JOIN
       table2 t2
       ON t2.id = tt1.id AND t2.column1 = tt1.column1
    SET t1.columX = (@position_temp := @position_temp + 1),
        t1.columY = 2,
        t1.columZ = 3,
        t2.columA = 0;