arielnmz
arielnmz

Reputation: 9145

How to replace ID in one table with corresponding value from another table?

Lets say I have a table like this:

+----------+-----------+-----------+
|   name   | color_id  | shape_id  |
+----------+-----------+-----------+
|    A     |     1     |     1     |
+----------+-----------+-----------+
|    B     |     2     |     2     |
+----------+-----------+-----------+
|    C     |     3     |     3     |
+----------+-----------+-----------+

And two other tables like these:

+----------+-------+
| color_id | color |
+----------+-------+
|    1     |   R   |
+----------+-------+
|    2     |   G   |
+----------+-------+
|    3     |   B   |
+----------+-------+

+----------+-------+
| shape_id | shape |
+----------+-------+
|    1     |   S   |
+----------+-------+
|    2     |   T   |
+----------+-------+
|    3     |   C   |
+----------+-------+

And I want to make a query and get this result set:

+----------+-----------+-----------+
|   name   |   color   |   shape   |
+----------+-----------+-----------+
|    A     |     R     |     S     |
+----------+-----------+-----------+
|    B     |     G     |     T     |
+----------+-----------+-----------+
|    C     |     B     |     C     |
+----------+-----------+-----------+

I think it has to do something with JOIN but I really don't know how to make it work.

Upvotes: 1

Views: 1740

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180808

SELECT 
   name, color, shape
FROM 
   table1
      INNER JOIN 
         table2 ON table1.color_id = table2.color_id
      INNER JOIN 
         table3 ON table1.shape_id = table3.shape_id

Upvotes: 3

Related Questions