n00b
n00b

Reputation: 192

When is it best to use JOIN or UNION?

Suppose I have three tables:

Primaries:

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

Dependents:

enter image description here

Transactions:

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

I am just wondering, what is the SQL operation that I have to use in order for me to get the passportId for each borrower? Should I use JOIN or UNION? And what would be the difference for the both of them given my schema above?

Output Expected:

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

Upvotes: 0

Views: 401

Answers (2)

gal peled
gal peled

Reputation: 482

UNION is combining 2 tables that have the same columns into one it will add one table under the other (will remove duplicate records) union all will leave the duplication

Join will add columns from 2 different columns tables by a specific logic

in you case you cannot use Union as None of the tables are the same you need to use Join

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

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271231

If I understand correctly, you want left joins and 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;

The first left join matches directly to the primaries table. The second matches through the dependents.

Upvotes: 1

Related Questions