加入具有另一个表的两个公共列的 postgres 表
Posted
技术标签:
【中文标题】加入具有另一个表的两个公共列的 postgres 表【英文标题】:Join postgres table that has two common columns of another table 【发布时间】:2022-01-18 18:57:02 【问题描述】:我有两张桌子:
Transactions:
+---------+--------------+------------+-----------+
| id | address_from | address_to | value |
+---------+--------------+------------+-----------+
| 1 | 1 | 2 | 1000 |
| 2 | 1 | 2 | 500 |
+---------+--------------+------------+-----------+
Addresses:
+---------+--------------+
| id | address |
+---------+--------------+
| 1 | address1 |
| 2 | address2 |
+---------+--------------+
我需要获取所有带有地址而不是 id 的交易:
SELECT * FROM transactions tr
JOIN addresses ad ON tr.address_from = ad.id OR tr.address_to = ad.id
WHERE tr.address_from = 1 OR tr.address_to = 1
然后我得到以下结果:
+---------+--------------+-----------+
| id | address | value |
+---------+--------------+-----------+
| 1 | address1 | 1000 |
| 1 | address1 | 1000 |
| 2 | address2 | 500 |
| 2 | address2 | 500 |
+---------+--------------+-----------+
但我需要这样的东西:
+---------+--------------+-------------+-----------+
| id | address_from | address_to | value |
+---------+--------------+-------------+-----------+
| 1 | address1 | address2 | 1000 |
| 2 | address1 | address2 | 500 |
+---------+--------------+-------------+-----------+
我怎样才能得到这个结果? 加入两列不是很贵吗?
【问题讨论】:
【参考方案1】:您可以尝试在同一张表上使用 2 个连接来获得预期的结果
SELECT tr.id,adf.address as address_from,adt.address as address_to,tr.value
FROM transactions tr
JOIN addresses adf ON tr.address_from = adf.id
JOIN addresses adt ON tr.address_to = adt.id
【讨论】:
哦,我什至没有考虑过这种可能性。但是,大量的连接将如何影响具有数百万条记录的表呢?以上是关于加入具有另一个表的两个公共列的 postgres 表的主要内容,如果未能解决你的问题,请参考以下文章