将具有两列的行转换为一列的两行

时间:2011-12-27 15:09:29

标签: sql postgresql join union

我有两列,confid1confid2。它们都具有相同的数据类型。

我不知何故需要将confid2带入confid1,但不能将它们连接起来。而是将其插入confid1下的新行。

原件:

confid1     confid2
AACII1C1    AACII1C2

我尝试过使用UNION,如下所示:

(SELECT confid1 as ID1 FROM dyndomrun)
UNION
(SELECT confid2 as ID2 FROM dyndomrun)

然后在confid1内返回confid2confid1的组合,这就是我要寻找的内容,如下所示:

confid1
AACII1C1
AACII1C2

现在,问题是另一个表中的一列与confid1confid2相关联,但它只是在一个列中而是多行。

现在,我尝试使用相同的UNION方法,只需将pdbcode添加到代码中,如下所示:

(SELECT confid1 as id1, conformer.pdbcode from dyndomrun, conformer where dyndomrun.confid1 = conformer.id)
UNION
(SELECT confid2 as id2, conformer.pdbcode from dyndomrun, conformer where dyndomrun.confid1 = conformer.id)

如果不是这样,它会返回重复的“pdbcode”值,如下所示:

confid1,    pdbcode
AACII1C1    2a4n
AACII1C2    2a4n

我希望它选择并返回与pdbcodeconfid1相关的confid2列,如下所示:

confid1,    pdbcode
AACII1C1    2a4n
AACII1C2    1b87

4 个答案:

答案 0 :(得分:1)

(SELECT confid1 as id1, conformer.pdbcode from dyndomrun, conformer where dyndomrun.confid1 = conformer.id)
UNION
(SELECT confid2 as id2, conformer.pdbcode from dyndomrun, conformer where dyndomrun.confid2 = conformer.id)

答案 1 :(得分:1)

您可以使连接条件跨越两者:

select  *
from    dyndomrun ddr
join    conformer as c
on      c.id in (ddr.confid1, ddr.confid2)

或者,您可以将联合移动到子查询,并将其连接到第二个表:

select  *
from    (
        select  confid1 as confid
        from    dyndomrun
        union all
        select  confid2 
        from    dyndomrun
        ) as ddr
join    conformer as c
on      c.id = ddr.confid

答案 2 :(得分:1)

使用confid2更改您的第二个JOIN以匹配?

(SELECT confid1 as id1, conformer.pdbcode 
from dyndomrun JOIN conformer 
           ON dyndomrun.confid1 = conformer.id)
UNION
(SELECT confid2 as id2, conformer.pdbcode 
 from dyndomrun JOIN conformer 
           ON dyndomrun.confid2 = conformer.id)

注意:已更新为使用显式JOIN语法

答案 3 :(得分:0)

SELECT A.confid1, B.pdbcode
FROM (  SELECT confid1 FROM dyndomrun
        UNION
        SELECT confid2 FROM dyndomrun) A
LEFT JOIN conformer B
ON A.confid1 = B.id