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

jobbol
seal-mask
.a{fill-rule:evenodd;}techdegree
jobbol
Full Stack JavaScript Techdegree Student 17,885 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.

task

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

area_name

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,932 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;