【问题标题】:MySQL JOIN different tables' columns in one columnMySQL在一列中加入不同表的列
【发布时间】: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 查询。
  • 谢谢,我已经添加了一些信息。

标签: mysql sql join


【解决方案1】:

找到解决办法:

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;

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • MySQL 说“未知列'location_name'”
    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 2015-04-03
    • 2013-10-20
    • 2015-08-30
    • 2015-09-09
    相关资源
    最近更新 更多