#1221 - Incorrect usage of UPDATE and ORDER BY

后端 未结 2 1835
名媛妹妹
名媛妹妹 2021-01-05 22:41

To bypass a problem I posted in a other thread. I tried an sql statement like this:

UPDATE user u JOIN (SELECT @i := 0) r
SET user_rank_planets = (@i := (@i          


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 22:52

    You cannot use order by and limit in update statement in the case of multiple tables.

    Quoting From MySQL Documentation:

    For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used.

    UPDATE user u 
    INNER JOIN 
    (
        SELECT 
        *,
        (@i := (@i + 1)) AS row_number
        FROM user u 
        CROSS JOIN (SELECT @i := 0) r
        WHERE user_active=1
        ORDER BY user_planets DESC
    )AS t
    ON u.Primary_key = t.primary_key
    SET u.user_rank_planets = t.row_number.
    

    Note: Replace u.Primary_key and t.primary_key by the primary key of user table.


    Read first few paragraphs http://dev.mysql.com/doc/refman/5.7/en/update.html

提交回复
热议问题