0

Having a hard time explaining my scenario and what I am trying to accomplish. I have two tables like so, I have reduced the values for my scenarios

Table1
+----------------------+
| ID |   Time          | 
+----------------------+
| 1 | 2018-05-15 09:00 |
| 1 | 2018-05-15 09:10 |
| 1 | 2018-05-15 09:20 |
| 2 | 2018-05-15 09:30 |
| 2 | 2018-05-15 09:40 |
+----------------------+
`
`
Table2
+----------------------+
| ID |   Time          | 
+----------------------+
| 1 | 2018-05-15 09:21 |
| 1 | 2018-05-15 09:31 |
| 2 | 2018-05-15 09:41 |
+----------------------+

I want to join these on the IDs but match on the latest result. By this I want the latest match ID from Table1 to Join with Latest match of ID with Table 2. So if I have a match of ID from both tables, I want the latest date to be displayed in the result and specify its coming from the other table. Once its used, the next match will get the latest unused date. Not familiar with looping through the results to handle this situation

The output I want to produce from the above query (Third column it to represent where that row comes from):

+----------------------+--------+
| ID |   Time          | Table  | 
+----------------------+--------+
| 1 | 2018-05-15 09:00 | Table1 |
| 1 | 2018-05-15 09:21 | Table2 | 
| 1 | 2018-05-15 09:31 | Table2 |
| 2 | 2018-05-15 09:30 | Table1 |
| 2 | 2018-05-15 09:41 | Table2 |
+----------------------+--------+
  • If you can't upgrade yet, see the tag I added. – Rick James Jul 1 '18 at 17:12
1

If you can upgrade to MariaDB version 10.2, you can use window functions.

The following assumes that table1 has - for every id - the same or more rows than table2:

WITH
  t1 AS
  ( SELECT id, time, 
           row_number() OVER (PARTITION BY id ORDER BY time DESC) AS rn
    FROM table1
  ), 
  t2 AS
  ( SELECT id, time, 
           row_number() OVER (PARTITION BY id ORDER BY time DESC) AS rn
    FROM table2
  )
SELECT 
    t1.id, 
    CASE WHEN t2.time IS NULL OR t1.time >= t2.time
        THEN t1.time ELSE t2.time
    END AS time,
    CASE WHEN t2.time IS NULL OR t1.time >= t2.time
        THEN 'table1' ELSE 'table2'
    END AS "table"
FROM
    t1 LEFT JOIN t2 
    ON  t1.id = t2.id
    AND t1.rn = t2.rn
ORDER BY
    id, t1.rn DESC ;

Tested at dbfiddle.uk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.