简体   繁体   中英

UPDATE multiple different tables with ORDER BY and LIMIT MYSQL

For starters I know that it is not possible and I have to use somehow select but am not sure how to do it. This is the query the I have now simplified.

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;

You cannot use ORDER BY in an UPDATE with a JOIN in MySQL. Assuming table1(id) and `table2(id, column1) are unique, this should work:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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