简体   繁体   中英

MySQL JOIN different tables' columns in one column

I have table with misc hardware data with columns "location_type" and "location_id" and two different tables with locations: rooms and people, both have columns "id" and "name". I need to get one row "location_name" in result, filled by matched room or people 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 |
+------------------+---------------+-------------+---------------+

How can I do that in MySQL? I've tried this:

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;
SELECT 
location, 
location_type, 
location_id, 
CASE location_type  WHEN 'room' THEN R.name WHEN 'people' THEN P.name END as location_name
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

Found a solution:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM