【发布时间】:2022-12-02 01:29:18
【问题描述】:
I have a scenario where two tables (table1 has columns Id and IDSuffix and table2 has columns TableID, TableIDSuffix and Name) have matching ID, but the suffix associated with ID may or may not present in Table2.
How to identify those suffixes which is present in table1, but absent in table2?
Table1
| ID | IDSuffix |
|---|---|
| 101 | 0 |
| 101 | 8 |
| 101 | 9 |
| 412 | 0 |
| 412 | 5 |
| 412 | 9 |
| 215 | 0 |
| 215 | 9 |
| 518 | 0 |
| 518 | 9 |
Table2
| TableID | TableIDSuffix | Name |
|---|---|---|
| 101 | 0 | Tom |
| 101 | 0 | Mel |
| 101 | 9 | Tom |
| 101 | 9 | Mel |
| 412 | 0 | Gab |
| 412 | 9 | Gab |
| 215 | 0 | Kit |
| 215 | 0 | Hary |
| 215 | 9 | Hary |
| 518 | 0 | Jo |
| 518 | 9 | J0 |
| 518 | 0 | Kia |
| 518 | 9 | Kia |
Required output should be like this:
| ID | IDSuffix | Name |
|---|---|---|
| 101 | 8 | Tom |
| 101 | 8 | Mel |
| 412 | 5 | Gab |
| 215 | 9 | Kit |
I used the left join in my query like this:
SELECT a.ID, a.IDSuffix, b.TableIDSuffix, b.Name
FROM Table1 a
LEFT JOIN Table2 b ON a.ID = b.TableID
AND a.IDSuffix = b.TableIDSuffix
GROUP BY a.ID, a.IDSuffix, b.TableIDSuffix, b.Name
I was expecting b.TableIDSuffix will be NULL so that I can extract those rows, but what I see for example for ID = 101 for IDSuffix 8 there is only one NULL in TableIDSuffix - there should be two for both Tom and Mel as shown in the expected result table.
Thanks for help
【问题讨论】:
标签: sql