Jeiman
Jeiman

Reputation: 1181

Join together pre-joined tables to one single table

I have two joined tables that i have joined up with other tables previously and i would like "ddid" to link up with "confid1"

Here is the code :

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;

and

(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)

At the end, I would like to have a new table containing domainid, dombegin, domend, ddid, confid1, pdbcode, chainid.

Is this possible to do because it threw me an error when i tried doing a union of a pre-joined table, stating that each UNION query must have the same number of columns.

Please advise. Thank you.

Upvotes: 0

Views: 983

Answers (2)

Andriy M
Andriy M

Reputation: 77657

If I understand you correctly:

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

Upvotes: 1

mikeY
mikeY

Reputation: 519

Wouldn't something like this work?

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

Probably be slow.

Upvotes: 0

Related Questions