Question

So after helpful feedback from my original question, I now have this query:

SELECT sessions.id, sessions.title, sessions.abstract, sessions.presenters, sessions.proposal_id, proposals.outcomes, proposals.CategorySelection, proposals.research3, proposals.research4, proposals.research5, proposals.research6, proposals.innovation3, proposals.innovation4, proposals.innovation5,proposals.innovation6, proposals.application3, proposals.application4, proposals.application5, proposals.application6, proposals.integration3, proposals.integration4, proposals.integration5, proposals.integration6, proposals.references, proposals.organization
    FROM sessions, proposals
    INNER JOIN proposals ON proposals.id = sessions.proposal_id
    WHERE sessions.id = '$id
    LIMIT 1;)

that is getting me nowhere fast. What am I doing wrong?


Original question: I need to pull several fields from one table and several more from a second table. The criteria is that a field called proposal_id match the id field of the second table. I am fairly new so this is what I have so far. It is not working, but not sure how to make it work.

(SELECT `title`,`abstract`,`presenters`,`proposal_id` FROM `sessions` WHERE   `id`='$id')
    UNION
    (SELECT `outcomes`,`CategorySelection`,`research3`,`research4`,`research5`,`research6`,`innovation3`,`innovation4`,`innovation5`,
        `innovation6`,`application3`,`application4`,`application5`,`application6`,`integration3`,`integration4`,`integration5`,`integration6`,`references`,`organization` FROM `proposals` WHERE `id`= `sessions`.`proposal_id`)
        LIMIT 1;
Was it helpful?

Solution

You need to use JOIN not UNION

select 
s.*,p.*
from `sessions` s
inner join `proposals` p on p.id = s.proposal_id
where s.id = '$id'

This is how you can join both the tables using the common key between.

You can select the specific fields instead of .* by specifying the column names as

s.col1,s.col2,p.col1,p.col2 

etc

OTHER TIPS

Try to use JOINS, where you can match the related fields from both the tables , this is the most convenient way to fetch records from multiple tables

UNION is used when you want to combine two queries

select a.id,b.some_field from table1 as a
INNER JOIN table2 as b ON b.prospal_id = a.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top