S
S
SergeySafaryanc2020-03-07 23:19:36
SQL
SergeySafaryanc, 2020-03-07 23:19:36

How to traverse history when joining tables?

There are two tables:

Table1(id, param1, param2, date_from, date_to):
(1, 'z', 55, '05/01/2010 12:30:20', '5/17/2010 13:10:14'),
( 1, 'c', null, '17.05.2010 13:10:15', '18.01.2010 04:13:15'),
(1, 'c', 25, '18.01.2010 04:13:16' , '01.01.9999 00:00:00');

Table2(id, param3, date_from, date_to):
(1, 15, '04/01/2010 12:30:20', '05/02/2010 13:10:14'),
(1, 35, '05/02/2010 13: 10:15', '01.01.9999 00:00:00');
It is necessary that when merging 2 tables there are fields containing the history of each parameter change. That is:

Select(id, param1, param2, param3, date_from, date_to):
(1, null, null, 10, '01.04.2010 12:30:20', '01.05.
(1, 'z', 55, 35, '02.05.2010 13:10:15', '17.05.2010 13:10:14'),
(1, 'c', null, 35, '17.05.2010 13 :10:15', '18.01.2010 04:13:15'),
(1, 'c', 25, 35, '18.01.2010 04:13:16', '01.01.9999 00:00:00' );
Where records from two tables did not intersect in time (or part of the time) null should be displayed.

So far I have done:

SELECT a.id, param1, param2, param3, a.dfrom as afrom, a.dto as ato, b.dfrom as bfrom, b.dto as bto
FROM Table1 a LEFT JOIN Table2 b ON a.id = b.id
UNION
SELECT id, null as param1, null as param2, param3, null as afrom, null as bfrom, dfrom, dto
FROM Table2
And then I don't understand how to proceed...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2020-03-07
SQL

cartesian product

R
Rsa97, 2020-03-08
@Rsa97

Since your time intervals do not match, the task is much easier to solve on the client, and not in MySQL.
The request, theoretically, can also be made, but it will be monstrous. There will be a UNION of several (at first glance, six) subqueries, each of which JOIN selects data depending on the overlap of time intervals of rows from both tables.
Well, the date must be converted to DATETIME, otherwise the cost of constant conversion will be added.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question