如何用一个表中的相应值替换一个表中的ID?

时间:2013-11-01 22:16:12

标签: php mysql sql database

假设我有一张这样的表:

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

另外两个表格如下:

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

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

我想进行查询并获得此结果集:

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

我认为它必须与JOIN做点什么,但我真的不知道如何让它发挥作用。

1 个答案:

答案 0 :(得分:2)

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