简体   繁体   中英

Mysql update query with multiple order by?

How can I get the following query to work as expected? MySQL gives me an error for the multiple ORDER BY

UPDATE user_list 
SET user_code = $code 
WHERE user_id = $id
AND country = $country AND 
     ((d = $d) OR 
     (c = $c ORDER BY c ASC LIMIT 1) OR
     (b = $b ORDER BY b ASC LIMIT 1))

The idea is the following:

If there is a user with user_id = $id AND country = $country AND d = $d then SET user_code = $code

If the above is false, then go and take THE 1st user ordered by c with user_id = $id AND country = $country AND c = $c and then do SET user_code = $code

If the above is false, then go and take THE 1st user ordered by b with user_id = $id AND country = $country AND b = $b and then do SET user_code = $code

You seem to want to update the row where the maximum value of c or b equals some value. You can do this with joins:

UPDATE user_list u CROSS JOIN
       (select max(c) as maxc, max(b) = maxb
        from user_list
        where user_id = $id AND country = $country
       ) uu
    SET user_code = $code
    WHERE user_id = $id AND country = $country AND
           ((d = $d) OR (c = maxc and c = $c) or (b = maxb and b = $b))

You can use a nested sql to find the first user ordered by c or b, I modified your original command.

UPDATE user_list 
SET user_code = $code 
WHERE user_id = $id
AND country = $country AND 
     ((d = $d) OR 
     ( $c = (select c from user_list order by c asc limit 1)) OR
     ( $b = (select b from user_list order by b asc limit 1)))

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