我有一张桌子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值,因为是max AG的价值。
答案 0 :(得分:0)
这为您提供了最大值
SELECT state, max(rating) as maxrating
FROM states_risk
GROUP BY state
这为您提供了要更新的内容
SELECT id, state
FROM states_risk
WHERE municiplally = 'OTHER'
所以更新是
UPDATE states_risk
SET rating = (
SELECT max(rating) as maxrating
FROM states_risk inner
WHERE inner.state = states_risk.state
)
WHERE municiplally = 'OTHER'
答案 1 :(得分:0)
您可以通过将表联接到返回每个州的最高评分的查询来做到这一点:
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 |
答案 2 :(得分:0)
如果您的列等级在其列中具有“-”。 您还需要铸造柱子 喜欢
select version();
| version() | | :-------- | | 8.0.18 |
CREATE TABLE states_risk (`id` int, `state` varchar(2), `municipally` varchar(5), `rating` varchar(3)) ; INSERT INTO states_risk (`id`, `state`, `municipally`, `rating`) VALUES (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', '-') ;
✓ ✓
Select * From states_risk;
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 | -
SELECT state, MAX(CAST(rating as FLOAT)) MAXrating FROM states_risk WHERE rating <> '-' GROUP BY state
state | MAXrating :---- | --------: AG | 6 AB | 10
UPDATE states_risk sr INNER JOIN (SELECT state, MAX(CAST(rating as FLOAT)) MAXrating FROM states_risk WHERE rating <> '-' GROUP BY state) t1 ON sr.state = t1.state SET sr.rating = t1.MAXrating WHERE sr.municipally = 'OTHER';
✓
Select * From states_risk;
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
db <>提琴here