tim_barber_7BB tim_barber_7BB - 2 months ago 9
MySQL Question

MYSQL Update Based On A Row Index Equaling An ID In Another Table

I have two tables. I'd like to update a row in table1 based on the same row index in table2. The IDs don't match but but the ID in table 2 matches the row index. There will always be more data in table 2, but I don't care if the extra rows are missed.

How would I achieve this in a mysql UPDATE statement?

table 1 ______________ table 2 _____________
Row number | id | value | Row number | id | value |
|--------------| |-----|-------|
1 | 2 | A | 1 | 1 | W |
2 | 4 | B | 2 | 2 | X |
3 | 6 | C | 3 | 3 | Y |
4 | 4 | Z |

to:
table 1 ______________
Row number | id | value |
|--------------|
1 | 2 | W |
2 | 4 | X |
3 | 6 | Y |

Answer

This works, but it's not pretty.

set @c=0;
update t1
join (
    select tx.id,t2.value
    from t2
    join (
        select @c:=@c+1 as rownum, value, id
        from (
            select * from t1  order by id
        ) t3
    ) tx
    on t2.id=tx.rownum) tupdate
on t1.id = tupdate.id
set t1.value=tupdate.value;

The basic point behind it is to use a variable to count rows, then use that to join. I ended up using multiple nested selects because the requirement is to update t1 but only after making a version of it with the rows counted.

The set at the start is required to stop it from overcounting if repeated. See MySQL - Get row number on select for the inspiration.