SQL内部联接,按时间戳记在两个表中

时间:2019-06-18 17:31:01

标签: sql inner-join

如何在两个不同的表中排序时间戳的内部联接输出?

| id |      event |                  timestamp |
------------------------------------------------
|  1 |     passed |        2019-06-05 11:55:44 |
|  1 |     failed |        2019-06-09 08:19:35 |


| id |      event |                  timestamp |
------------------------------------------------
|  1 | email_sent |        2019-06-05 11:56:44 |
|  1 | email_sent |        2019-06-09 08:20:35 |

所需结果:

| id |      event |                  timestamp |
------------------------------------------------
|  1 |     passed |        2019-06-05 11:55:44 |
|  1 | email_sent |        2019-06-05 11:56:44 |
|  1 |     failed |        2019-06-09 08:19:35 |
|  1 | email_sent |        2019-06-09 08:20:35 |

这是我到目前为止的内容,但是它按时间戳对TableA进行排序,然后按时间戳对TableB进行排序,而不是一次对所有时间戳进行排序:

SELECT TableA.*, TableB.* FROM TableA 
        INNER JOIN TableB ON TableA.id=TableB.id
        WHERE TableA.id='1' ORDER BY TableA.timestamp, TableB.timestamp

1 个答案:

答案 0 :(得分:2)

您要union all

select id, event, timestamp 
from tablea
union all
select id, event, timestamp 
from tableb
order by timestamp;

如果要过滤行,可以将where id = 1添加到每个子查询。