显示指向同一个表的两个id字段的两个链接值

问题描述 投票:0回答:2

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

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

link1link2字段都指向同一个表table2,其中有iddescr字段。

我会创建一个SQL查询,返回相同的行id和两个字段的descr值,如下所示:

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

我尝试了不同的查询,但每个id返回两行而不是一行。如何在PostgreSQL 9.04数据库中实现这些结果?

sql postgresql self-join
2个回答
2
投票

通常,此查询应该适合您。假设您的第一个表名为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;

0
投票

你可以在这里使用案例赞:

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
© www.soinside.com 2019 - 2024. All rights reserved.