MySQL在一列中加入不同表的列

时间:2015-02-13 12:16:39

标签: mysql sql join

我有带有“location_type”和“location_id”列的misc硬件数据表和两个带位置的不同表:房间和人,都有“id”和“name”列。我需要在结果中获得一行“location_name”,由匹配的房间或人名填充。

table_equipment
+------------------+---------------+-------------+
| name             | location_type | location_id |
+------------------+---------------+-------------+
| ASUS P9X79 LE    | room          |           1 |
| 8 x Intel Core z | room          |           2 |
| GeForce GTX 680  | people        |           2 |
+------------------+---------------+-------------+

table_rooms
+------------------+----+
| name             | id |
+------------------+----+
| Vault            |  1 |
| Kitchen          |  2 |
+------------------+----+

table_people
+------------------+----+
| name             | id |
+------------------+----+
| John             |  1 |
| Maria            |  2 |
+------------------+----+


Result:
+------------------+---------------+-------------+---------------+
| name             | location_type | location_id | location_name |
+------------------+---------------+-------------+---------------+
| ASUS P9X79 LE    | room          |           1 |         Vault |
| 8 x Intel Core z | room          |           2 |       Kitchen |
| GeForce GTX 680  | people        |           2 |         Maria |
+------------------+---------------+-------------+---------------+

我怎样才能在MySQL中这样做?我试过这个:

SELECT t_eq.*, t_ppl.name AS loc_name, t_rm.name AS loc_name
FROM table_equipment AS t_eq
LEFT JOIN table_people AS t_ppl ON (t_eq.location_id=t_ppl.id AND t_eq.location_type='people')
LEFT JOIN table_rooms AS t_rm ON (t_eq.location_id=t_rm.id AND t_eq.location_type='room')
WHERE t_eq.location_type=0 OR t_eq.location_type=1 ORDER BY id;

2 个答案:

答案 0 :(得分:0)

SELECT 
location, 
location_type, 
location_id, 
location_name = CASE location_type  WHEN 'room' THEN R.name WHEN 'people' THEN P.name END
FROM Equipment E
LEFT OUTER JOIN Rooms R
ON E.location_id = R.id
LEFT OUTER JOIN People P
ON E.location_id = P.id

答案 1 :(得分:0)

找到解决方案:

SELECT t_eq.*, CASE t_eq.location_type
                       WHEN 0 THEN t_ppl.name
                       WHEN 1 THEN t_rm.name END
               AS location_name
FROM table_equipment AS t_eq
LEFT OUTER JOIN table_people AS t_ppl ON t_eq.location_id = t_ppl.id
LEFT OUTER JOIN table_rooms AS t_rm ON t_eq.location_id = t_rm.id;