sql—将表中的两个ID匹配到不同的表pgsql

gajydyqb  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(336)

所以,这里有一个汇率表,有fromcurr\u id和tocurr\u id,根据id的货币名称是另一个表currency。

exchng_rate_id | fromcurr_id | tocurr_id | exchange_rate 
----------------+-------------+-----------+---------------
              1 |           1 |         2 |  5.0000000000
              2 |           1 |         3 |  3.0000000000
              3 |           1 |         4 |  6.0000000000
              4 |           1 |         5 |  2.0000000000
              5 |           2 |         3 |  5.0000000000
              6 |           2 |         4 |  7.0000000000
              7 |           2 |         5 |  3.0000000000
              8 |           3 |         4 |  1.0000000000
              9 |           3 |         5 |  4.0000000000
             10 |           4 |         5 |  2.0000000000

以下是货币表的说明:

Column  |          Type          | Collation | Nullable |               Default                
---------+------------------------+-----------+----------+--------------------------------------
 id      | integer                |           | not null | nextval('currency_id_seq'::regclass)
 curr_id | integer                |           | not null | 
 name    | character varying(255) |           |          |

我需要显示哪个id属于哪个货币名称(即fromcurr\u id=name和tocurr\u id=name)
这就是我试过的。。。
query1:尝试对表进行内部联接,但结果只生成fromcurr\u id的名称。

select name, fromcurr_id, tocurr_id, name, exchange_rate 
from exchange_rate 
  inner join currency on exchange_rate.fromcurr_id = currency.curr_id;

结果:

name      | fromcurr_id | tocurr_id |      name      | exchange_rate 
----------------+-------------+-----------+----------------+---------------

**************|           1 |         2 |**************|  5.0000000000
**************|           1 |         3 |**************|  3.0000000000
**************|           1 |         4 |**************|  6.0000000000
**************|           1 |         5 |**************|  2.0000000000
*************|           2 |         3 |************ |  5.0000000000
************ |           2 |         4 |**************|  7.0000000000
*************|           2 |         5 |************ |  3.0000000000
**************|           3 |         4 |**************|  1.0000000000
**************|           3 |         5 |**************|  4.0000000000
**************|           4 |         5 |**************|  2.0000000000

(10 rows)

第一种情况下的名称与第二种情况下的名称相同,并且与货币表不同(必须审查数据以保密)
query2:尝试了两个条件的内部连接。

select name, fromcurr_id, tocurr_id, name, exchange_rate 
from exchange_rate 
  inner join currency on exchange_rate.fromcurr_id = currency.curr_id 
                     and exchange_rate.tocurr_id = currency.curr_id;

这没有结果。

inb24sb2

inb24sb21#

你需要两个 join s、 每种货币一个:

select er.*, cfrom.*, cto.*
from exchange_rate er inner join
     currency cfrom
     on er.fromcurr_id = cfrom.curr_id join
     current cto
     on er.tocurr_id = eto.curr_id

相关问题