MySQL: replace column values ​​with values ​​in nearest new table

I have two tables:

Table1 (ID, Kilometers, Depth)
Table2 (ID, Kilometers, Depth)

Sample Data:
Table 1
1, 0.001, 10
2, 0.002, 11
3, 0.003, 11

Table 2
1, 0.001, 10
2, 0.003, 12
3, 0.004, 15

I need to replace the depth in table 1 with the depth in table 2 according to its Kilometers value.

However, table 2 may not have the value of kilometers for everyone in table 1. Therefore, I need to get the closest value (per kilometer) and use its depth in the replacement.

I was hoping this would be a single SQL statement. Just a direct replacement would be like this:

UPDATE T1, T2 SET T1.Depth = T2.Depth WHERE T1.Kilometers = T2.Kilometers

Anyway, can I adapt this to get the closest value?

+3
source share
2 answers

It is simple and does what you want:

UPDATE table1 SET depth = (
     SELECT depth FROM table2 
     ORDER BY (ABS(table1.kilometers-table2.kilometers)) ASC 
     LIMIT 1
);

-- Query OK, 2 rows affected (0.00 sec)

mysql> select * from table1;
+----+------------+-------+
| id | kilometers | depth |
+----+------------+-------+
|  1 |      0.001 |    10 |
|  2 |      0.002 |    10 |
|  3 |      0.003 |    12 |
+----+------------+-------+
0
source
update tbl1
inner join (
    select tbl1.id,
        (
            select id
            from tbl2
            order by abs(tbl2.Kilometers - tbl1.Kilometers) asc
            limit 1
        ) AS tbl2id
    from tbl1
) X
    on tbl1.id = X.id
inner join tbl2
    on tbl2.id = X.tbl2id

set tbl1.depth = tbl2.depth;

: tbl1 tbl2 - . X - , , tbl1.id. tbl2id - id tbl2, tbl1.id, .

0

Source: https://habr.com/ru/post/1789937/


All Articles