【发布时间】:2022-01-27 18:20:21
【问题描述】:
我有两张桌子
T1:
| ID | Reference | Status | Event Timestamp |
|---|---|---|---|
| 1 | Flowers | Dispatched | 2021-12-10 |
| 2 | Flowers | Delivered | 2021-12-11 |
和T2:
| ID | Reference | Comments | Event Timestamp |
|---|---|---|---|
| 1 | Flowers | well done | 2021-12-12 |
| 2 | Flowers | go on | 2021-12-13 |
| 3 | Pot | random | 2021-12-13 |
我试图通过查询 Flowers 参考的表格是(使用 Postgres)
| t1_ID | t2_ID | Reference | Comments | Status | t1_Event Timestamp | t2_Event Timestamp |
|---|---|---|---|---|---|---|
| 1 | null | Flowers | null | Dispatched | 2021-12-10 | null |
| 2 | null | Flowers | null | Delivered | 2021-12-11 | null |
| null | 1 | Flowers | well done | Delivered | 2021-12-11 | 2021-12-12 |
| null | 2 | Flowers | go on | Delivered | 2021-12-11 | 2021-12-13 |
换句话说,我需要一个连接表来记录两个表之间的所有更新。
我尝试了许多查询,例如 LEFT JOIN、UNION 等,但所有尝试均不成功。
您能否建议我应该使用哪些 SQL 语句来获得预期的结果?
【问题讨论】:
-
您到底想做什么?只需将两个表中所有 Flowers 引用的结果显示在一个表中?
-
没错,但是如果我使用简单的 JOIN,它将不会返回 Comments 为空的行。
-
@RDK 为什么 t1_id = 2 表示来自 T2 的行?不应该是NULL吗?
-
@Blue_Elephant 基本上对于每个 T1 行,我需要检查 T2 中是否有一个具有相同引用和 LOWER-EQUAL T2_event 时间戳的条目
-
@Zakaria 你是对的,我编辑了它。
标签: sql postgresql