Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Development Tools

geoffrey
geoffrey
28,736 Points

Combine two SQL queries

Hi there, I'm working on a projet at the moment and I have difficulties to retrieve in one query all the needed datas from 3 differents tables.

I can get the datas I need using two differents queries, I tried to combine both of them using the UNION keyword in my query, but it doesn't seem to work.

Here is the two queries separated, giving the datas I need, the challenge for me is to combine both in one query, till now I haven't succeed hence this post..

SELECT b.ID_bug,b.date,b.author,b.app_url,b.app_version,
b.title,b.description,b.img,b.priority,b.last_action,
l.name AS label_name ,l.color AS label_color
FROM t_bugs b JOIN t_labels l ON FK_label_ID = ID_label
WHERE id_bug = 2 ;

SELECT  b.ID_bug,b.date,b.author,b.app_url,b.app_version,
b.title,b.description,b.img,b.priority,b.last_action,
d.pseudo FROM t_bugs b JOIN t_devs d ON FK_dev_ID =  ID_dev
WHERE id_bug = 2;

2 Answers

Stone Preston
Stone Preston
42,016 Points

I think you just need to use a double join. join t_bugs and t_lables together. then join t_devs to that.

SELECT 
b.ID_bug,b.date,b.author,b.app_url,b.app_version,
b.title,b.description,b.img,b.priority,b.last_action,
l.name AS label_name ,l.color AS label_color
FROM t_bugs b 
JOIN t_labels l ON FK_label_ID = ID_label
JOIN t_devs d ON FK_dev_ID =  ID_dev
WHERE id_bug = 2;
geoffrey
geoffrey
28,736 Points

That was so simple, I was pretty sure once I I had done the first JOIN, I couldn't do another one... Thank you man :)

This StackOverflow article on querying multiple tables goes into a lot of detail about the difference between JOIN and UNION and when to use each.