sqlmergemariadbtimestamp

Merge tables with different timestamps?


I have two tables A and B. (Synology NAS, MariaDB if this is important)

Table A gets a new record every minute, table B gets a new record about every 2 minutes. Since table B has less entries I want to merge B into A. The problem is: the timestamps and also column names don't match!

Now I would like to have a query which matches the timestamp from B to the closest timestamp from A without creating duplicates or new rows.

Is this possible with a single query?

Example:

Table A

date abc
2025-10-17 14:11:14 0
2025-10-17 14:12:11 0
2025-10-17 14:13:18 0
2025-10-17 14:14:15 0
2025-10-17 14:15:10 0
...

Table B

date_x xyz
2025-10-17 14:12:26 11
2025-10-17 14:14:20 22
...

Table A Merged

date abc
2025-10-17 14:11:14 0
2025-10-17 14:12:11 11
2025-10-17 14:13:18 0
2025-10-17 14:14:15 22
2025-10-17 14:15:10 0
...

Solution

  • The main question is how to match the rows of Table A and Table B.
    I will assume that if the difference is less than 30 seconds, the rows can be considered comparable.

    See example

    select *
    from TableA a
    left join TableB b 
      on b.date between (a.date- interval 30 second) and (a.date+ interval 30 second)
    
    date abc date xyz
    2025-10-17 14:11:14 0 null null
    2025-10-17 14:12:11 0 2025-10-17 14:12:26 11
    2025-10-17 14:13:18 0 null null
    2025-10-17 14:14:15 0 2025-10-17 14:14:20 22
    2025-10-17 14:15:10 0 null null

    The actual update

    Update TableA a,TableB b 
    set a.abc=b.xyz
    where b.date between (a.date- interval 30 second) and (a.date+ interval 30 second)
    
    select * from TableA;
    
    date abc
    2025-10-17 14:11:14 0
    2025-10-17 14:12:11 11
    2025-10-17 14:13:18 0
    2025-10-17 14:14:15 22
    2025-10-17 14:15:10 0

    fiddle