如何让以下查询按预期工作? MySQL给出了多个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))
这个想法如下:
如果有用户user_id = $id AND country = $country AND d = $d
,则SET user_code = $code
如果上述情况属于假,那么请使用user_id = $id AND country = $country AND c = $c
进行按c 订购的第一位用户,然后执行SET user_code = $code
如果上述情况属于假,那么请使用user_id = $id AND country = $country AND b = $b
继续由b 订购的第一位用户,然后执行SET user_code = $code
答案 0 :(得分:3)
您似乎想要更新c或b的最大值等于某个值的行。您可以使用连接执行此操作:
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))
答案 1 :(得分:2)
您可以使用嵌套的sql查找按c或b排序的第一个用户,我修改了您的原始命令。
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)))