【发布时间】:2015-02-13 12:16:39
【问题描述】:
我有一个包含杂项硬件数据的表,其中包含“location_type”和“location_id”列以及两个不同的包含位置的表:房间和人员,它们都有“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;
【问题讨论】:
-
如果您需要有关此问题的帮助,请编辑您的问题并 (1) 从您的表格中添加示例数据; (2) 添加您希望看到的结果; (3) 添加您尝试解决问题的任何 SQL 查询。
-
谢谢,我已经添加了一些信息。