将预先连接的表连接到一个表中

时间:2011-12-27 18:48:35

标签: sql postgresql join union

我有两个已加入的表格,我之前与其他表格相关联,我希望“ddid”与“confid1”链接

以下是代码:

SELECT r.domainid, r.dombegin, r.domend, d.ddid 
FROM   domainregion AS r
JOIN   dyndomrun AS d ON r.domainid::varchar(8) = d.ddid 
ORDER  BY r.domainid, d.ddid, r.dombegin, r.domend;

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

最后,我想要一个包含domainid,dombegin,domend,ddid,confid1,pdbcode,chainid的新表。

这样做是否可行,因为当我尝试执行预连接表的并集时,它会向我提出错误,指出每个UNION查询必须具有相同的列数。

请指教。谢谢。

2 个答案:

答案 0 :(得分:1)

如果我理解正确的话:

SELECT
  r.domainid,
  r.dombegin,
  r.domend,
  d.ddid,
  d.confid1 AS confid,
  c.pdbcode,
  c.chainid
FROM dyndomrun d
  INNER JOIN conformer c ON d.confid1 = c.id
  INNER JOIN domainregion r ON r.domainid::varchar(8) = d.ddid
UNION ALL
SELECT
  NULL,
  NULL,
  NULL,
  d.ddid,
  d.confid2,
  c.pdbcode,
  c.chainid
FROM dyndomrun d
  INNER JOIN conformer c ON d.confid2 = c.id

答案 1 :(得分:0)

不会有这样的工作吗?

select domainid, dombegin, domened, ddid, confid_id, pdbcode, chainid
from (
SELECT r.domainid, r.dombegin, r.domend, d.ddid  
FROM   domainregion AS r JOIN   dyndomrun AS d ON r.domainid::varchar(8) = d.ddid
ORDER  BY r.domainid, d.ddid, r.dombegin, r.domend
) first 
inner join (
(SELECT confid1 as confid_id, conformer.pdbcode, conformer.chainid 
 from dyndomrun JOIN conformer ON dyndomrun.confid1 = conformer.id) 
 UNION
(SELECT confid2 as confid_id, conformer.pdbcode, conformer.chainid
 from dyndomrun JOIN conformer ON dyndomrun.confid2 = conformer.id) 
) second 
on first.ddid=second.confid_id

可能很慢。