Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Josh Olson
Josh Olson
13,236 Points

How to select and join two tables but replace IDs with matching values?

I have two tables: task and area_name. I need a select which gets everything from the task table, but replaces the ID value with the matching name from the name table.


area_id  |  description   |   ...
1        |  Mow lawn      |
2        |  Clean dishes  |
4        |  Fold clothes  |


area_id |  name
1       |  Yard
2       |  Kitchen
3       |  Living room
4       |  Laundry room

wanted result

area          |  description   |   ...
Yard          |  Mow lawn      |
Kitchen       |  Clean dishes  |
Laundry room  |  Fold clothes  |

My code looks like this,

SELECT * FROM `task` as t1
LEFT JOIN `area_name` as t2 ON t1.area_id = t2.area_id;

But this returns

area_id  |  description   |   ...  | area_id  | area          |
1        |  Mow lawn      |        | 1        | Yard          |
2        |  Clean dishes  |        | 2        | Kitchen       |
4        |  Fold clothes  |        | 4        | Laundry room  |

Obviously there's an easy solution by picking the columns that select returns,

SELECT name AS area, description FROM `task` as t1
LEFT JOIN `area_name` as t2 ON t1.area_id = t2.area_id;

However I'm not looking to list each column in the query, as my task table in reality is 12 columns or so long, and I don't want to maintain this as I change the schema. I'm looking for a shortcut if it's possible.

1 Answer

ivana kantnerova
ivana kantnerova
15,360 Points

i think should be like this ..

select t2.name as area, t1.description from task as t1 inner join area_name as t2 on t1.area_id = t2.area_id;