【发布时间】:2022-01-24 18:15:12
【问题描述】:
如何从 table_1 中找到唯一的电话号码(并将它们折叠成一列)(同时保留 ID 和日期字段),并删除出现在 table_2 中的电话号码?
table_1
| ID | phone1 | phone2 | date |
|---|---|---|---|
| 1 | 1111111111 | 2021-12-31 | |
| 5 | 2222222222 | 3333333333 | 2020-11-08 |
| 8 | 5555555555 | 2021-03-15 | |
| 14 | 7777777777 | 8888888888 | 2016-10-20 |
table_2
| ID | phone1 | phone2 | date |
|---|---|---|---|
| 567 | 4444444444 | 1111111111 | 2020-11-28 |
| 660 | 8888888888 | 2018-01-01 | |
| 898 | 9999999999 | 2017-04-06 |
无论电话出现在哪个电话列中,我都想将其从最终结果中删除。因此 ID 1 与电话 1111111111 将被删除,因为它在表 2 的电话 2 中
期望的输出
| ID | phone num | date |
|---|---|---|
| 5 | 2222222222 | 2020-11-08 |
| 5 | 3333333333 | 2020-11-08 |
| 8 | 5555555555 | 2021-03-15 |
| 14 | 7777777777 | 2016-10-20 |
到目前为止,我所拥有的似乎可行的就是这个。不过,我觉得必须有一种更有效的方法来做到这一点。
select * from (
select id, phone1 as phone_num, date from table_1
union all
select id, phone2 as phone_num, date from table_1
) tmp
where phone_num not in (
select phone1 as phone_num from table_2
union all
select phone2 as phone_num from table_2
)
order by id desc;
【问题讨论】:
-
添加一个位置以排除 phone2 中“空白”/null 的那些。除此之外;这很容易阅读/维护,我没有看到任何显着的性能改进。我想您可以使用 EXCEPT 而不是 where from table_2 ,因为它是一个集合运算符,并且可能效率更高。
-
EXCEPT 子句具有这种一般形式:
select_statement EXCEPT [ ALL ] select_statementpostgresql.org/docs/7.4/sql-select.html 但是你所说的“高效”高效写作是什么意思?执行以获得绩效?高效且易于阅读...有很多方法可以实现...
标签: sql postgresql