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

Databases

Eylon Cohen
Eylon Cohen
4,779 Points

Joining the same table (on different column) in order to screen out more resoluts ?

Hello, I will explain my question with a basic example:

I have table 1 with the colums ID, A and B (all int). I have table 2 with the column ID (int of course). I would like to produce a table (using SELECT) showing the IDs of the lines from table 1 that the values in both their column A and B cells are IDs from table 2 (value in A can be different than value in B, but both are from table 2).

If it was only one column I would of course use a simple Join. but with 2 columns I'm not sure what to do. I know I can use a subquery, but I was wondering if there is a simple way to do that, without a subquery.

Thank you!

1 Answer

Steven Parker
Steven Parker
231,128 Points

You can have two JOINs of the same tables with different criteria:

SELECT t.* FROM table1 t
JOIN table2 x ON t.A = x.ID
JOIN table2 y ON t.B = y.ID

Now please tell me I did not just do your homework. :open_mouth: