显示指向相同的两个 id 字段的两个链接值 table

Display two linked values for two id field pointing the same table

在我的 PostgreSQL 数据库中,我有一个像这样的 table:

id|link1|link2|
---------------
1 | 34  | 66
2 | 23  | 8
3 | 11  | 99

link1link2 字段都指向相同的 table table2,其中有 iddescr 字段。

我会做一个 SQL 查询 returns 同一行 iddescr 两个字段的值,如下所示:

id|link1|link2|desc_l1|desc_l2|
-------------------------------
1 | 34  |66  | bla  | sisusj|
2 | 23  | 8  | ghhj | yui   |
3 | 11  | 99 | erd  |  bnbn |

我尝试了不同的查询,但每个人 returns 每 id 两行而不是一行。 我怎样才能在我的 PostgreSQL 9.04 数据库中获得这些结果?

通常情况下,此查询应该适合您。假设您的第一个 table 名字是 table_name.

SELECT t.id, t.link1, t.link2, 
    l1.descr AS desc_l1,
    l2.descr AS desc_l2
FROM table_name t 
LEFT JOIN table2 l1
ON t.link1 = l1.id
LEFT JOIN table2 l2
ON t.link2 = l2.id;

你可以在这里用例 Like:

select link1,link2,
case
 when link1='34' and link2='66' then 'bla'
  when link1='23' and link2='8' then 'ghs'
   when link1='11' and link2='99' then 'erd'
end as desc_li,
case
 when link1='34' and link2='66' then 'sjm'
   when link1='23' and link2='8' then 'yur'
   when link1='11' and link2='99' then 'bnn'
end as desc_l2

from table1