使用另一个表中的数据选择和替换列值

时间:2016-03-20 04:25:13

标签: mysql

我的表设置如下:

Fruits:
ID | Name
---+-----
 1 | Apple
 2 | Orange
 3 | Banana
 4 | Lemon

Groups
ID | Name | Fruit1 | Fruit2 | Fruit3
---+------+--------+--------+-------
 1 |   A  |    1   |    2   |    3
 2 |   B  |    1   |    3   |  NULL
 3 |   C  |    4   |  NULL  |  NULL 

我想要的是从群组中选择并获取水果名称而不是其ID:

ID | Name | Fruit1 | Fruit2 | Fruit3
---+------+--------+--------+-------
 1 |   A  | Apple  | Orange | Banana
 2 |   B  | Apple  | Banana |  NULL
 3 |   C  | Lemon  |  NULL  |  NULL 

可以这样做吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT
    G.ID,
    G.Name ,
    (SELECT Name FROM Fruits WHERE ID=G.Fruit1) AS Fruit1, 
    (SELECT Name FROM Fruits WHERE ID=G.Fruit2) AS Fruit2 ,
    (SELECT Name FROM Fruits WHERE ID=G.Fruit3) AS Fruit3  
FROM 
    Groups G