我有一张桌子states_risk

id | state | municipally | rating


例:

id | state | municipally | rating
 1     AG     AG1            5
 2     AG     AG2            6
 3     AG     AG3            2
 4     AG     AG4            1
 5     AG     OTHER          -
 6     AB     AB1            0.2
 7     AB     AB2            2
 8     AB     AB3            10
 9     AB     OTHER          -


我需要更新状态municipally = OTHER的值“ rating”,并通过状态“ AG”-“ AB”设置MAX(rating)值,例如:id 5设置一个6值,因为它是状态AG的最大值。

最佳答案

您可以通过将表联接到返回每个州的最高评分的查询来做到这一点:

update states_risk s inner join (
  select state, max(rating) rating
  from states_risk
  group by state
) g on g.state = s.state
set s.rating = g.rating
where s.municipally = 'OTHER';


请参见demo
结果:

| id  | state | municipally | rating |
| --- | ----- | ----------- | ------ |
| 1   | AG    | AG1         | 5      |
| 2   | AG    | AG2         | 6      |
| 3   | AG    | AG3         | 2      |
| 4   | AG    | AG4         | 1      |
| 5   | AG    | OTHER       | 6      |
| 6   | AB    | AB1         | 0.2    |
| 7   | AB    | AB2         | 2      |
| 8   | AB    | AB3         | 10     |
| 9   | AB    | OTHER       | 10     |

关于mysql - 用另一列最大值更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59146619/

10-16 08:21