The problem can be simplified as follows:
Original state:
id type val
---------------
1 1 300
2 1 200
3 1 100
4 2 10
5 2 20
6 2 30
Desired state - for a range of id
s (here 3 to 4), update val
so that it's equal to the maximum val
for the given type
:
id type val
---------------
1 1 300
2 1 200
3 1 300 <--
4 2 30 <--
5 2 20
6 2 30
So only rows 3 and 4 were updated, maximum val
for type
1 is 300, for type
2 it's 30.
I thought it's an easy update, but I can't get it to work.
Here's the table definition and data:
create table test (id integer primary key, type integer, val integer);
insert into test (id, type, val) values (1, 1, 300);
insert into test (id, type, val) values (2, 1, 200);
insert into test (id, type, val) values (3, 1, 100);
insert into test (id, type, val) values (4, 2, 10);
insert into test (id, type, val) values (5, 2, 20);
insert into test (id, type, val) values (6, 2, 30);
And here's what I thought would work:
update test t1 set t1.val=(
select max(t2.val) from (
select * from test where type=t1.type
) t2
) where id>=3 and id<5;
However MySQL gives the error:
Unknown column 't1.type' in 'where clause'
I've found some answers to similar problems suggesting rewriting the update so that it uses JOIN, but I'm not sure how to do that - my attempt resulted in an error message about a nonexisting table. Please tell me what I'm missing.
Try this query:
UPDATE test t1 INNER JOIN
(SELECT TYPE,MAX(val) mval FROM test GROUP BY TYPE) t2
ON t1.type=t2.type
SET t1.val=t2.mval
WHERE t1.id BETWEEN 3 AND 4;
Fiddle here : https://www.db-fiddle.com/f/7Sn9aDBPze7pVvHNHFzQ1u/2