什么时候使用 JOIN 或 UNION 最好?

When is it best to use JOIN or UNION?

假设我有三个表:

初选:

| id | uuid | passportId | name |
|:---- |:------:| -----:|-----:|
| 1  | uuid-1111 | passportId1 | A Primary |
| 2  | uuid-2222 | passportId2 | Another Primary |

家属:

交易:

| id | borrowerUuid (FK: Primaries.uuid & Dependents.uuid) |
|:---- |:------:|
| 1  | uuid-1111 |
| 2  | uuid-3333 |
| 3  | uuid-4444 |

我只是想知道,我必须使用什么 SQL 操作才能为每个借款人获取 passportId?我应该使用 JOIN 还是 UNION?鉴于我上面的模式,它们两者会有什么区别?

预期输出:

| transactionId | borrowerUuid | name | primaryPassportId |
|:---- |:------:| -----:|-----:|
| 1  | uuid-1111 | A Primary | passportId1 |
| 2  | uuid-3333 | A Dependent  | passportId1 |
| 3  | uuid-4444 | Another Dependent  | passportId2 |

如果我没理解错的话,你想要 left joins 和 coalesce():

select t.*, coalesce(p.passportid, dp.passportid) as passportid
from transactions t left join
     primaries p
     on t.borroweruuid = p.uuid left join
     dependents d
     on t.borroweruuid = d.uuid left join
     primaries pd
     on pd.id = d.primaryid;

第一个 left join 直接匹配 primaries table。第二个匹配通过 dependents.

UNION 将具有相同列的 2 个 table 合并为一个,它将在另一个下添加一个 table(将删除重复记录)union all 将保留重复

Join 将通过特定逻辑

添加来自 2 个不同列 table 的列

在你的情况下你不能使用 Union 因为 None 的 table 是相同的 你需要使用 Join

select t.*, p.passportid, p.passportid , p.name
from transactions t left join
     primaries p
     on t.borroweruuid = p.uuid