在恶劣的表上加入MySQL表

Jak*_*Jak 2 mysql sql join concatenation

我继承了我的怀疑是一些劣质的SQL表的设计,并作为SQL新手,我挣扎拿出一个查询的加入和连接的数据.

以下是包含数据的两个表:

user_space:
+----+---------+---------+---------+----------+----------+----------+
| id | space_1 | space_2 | space_3 | units_s1 | units_s2 | units_s3 |
+----+---------+---------+---------+----------+----------+----------+
|  1 |     128 |     128 |       6 |        3 |        3 |        4 |
|  2 |       1 |     128 |       2 |        4 |        3 |        4 |
|  3 |     100 |     100 |     100 |        3 |        3 |        3 |
+----+---------+---------+---------+----------+----------+----------+
space_units:
+------+--------------+
| type | description  |
+------+--------------+
|    1 | KB           |
|    2 | MB           |
|    3 | GB           |
|    4 | TB           |
+------+--------------+
Run Code Online (Sandbox Code Playgroud)

这是我希望能够产生的:

+----+---------+---------+---------+
| id | total_1 | total_2 | total_3 |
+----+---------+---------+---------+
|  1 |   128GB |   128GB |     6TB |
|  2 |     1TB |   12GB8 |     2TB |
|  3 |   100GB |   100GB |   100GB |
+----+---------+---------+---------+
Run Code Online (Sandbox Code Playgroud)

user_space表中的最后3个"units_s*"列与space_units表中的"type"列相关.

有谁可以帮我一个合适的查询?我现在已经多年了,无法弄明白.不幸的是,我不允许丢弃表并正确实现它们.

Adr*_*ian 6

select 
    us.id, 
    concat(trim(us.space_1), trim(su1.description)) as total_1,
    concat(trim(us.space_2), trim(su2.description)) as total_2,
    concat(trim(us.space_3), trim(su3.description)) as total_3
from user_space us
inner join space_units su1 on (us.units_s1 = su1.type)
inner join space_units su2 on (us.units_s2 = su2.type)
inner join space_units su3 on (us.units_s3 = su3.type)
order by us.id

+----+---------+---------+---------+
| id | total_1 | total_2 | total_3 |
+----+---------+---------+---------+
|  1 | 128GB   | 128GB   | 6TB     |
|  2 | 1TB     | 128GB   | 2TB     |
|  3 | 100GB   | 100GB   | 100GB   |
+----+---------+---------+---------+
Run Code Online (Sandbox Code Playgroud)

编辑:使用格式文本作为表来格式化输出

create table user_space
(
 id integer,
 space_1 char(5),
 space_2 char(5),
 space_3 char(5),
 units_s1 integer,
 units_s2 integer,
 units_s3 integer
);
insert into user_space values (1, 128,128,6, 3, 3, 4);
insert into user_space values (2, 1,128,2, 4, 3, 4);
insert into user_space values (3, 100,100,100, 3, 3, 3);
create table space_units
(
type integer,
description char(5)
);
insert into space_units values (1, 'KB');
insert into space_units values (2, 'MB');
insert into space_units values (3, 'GB');
insert into space_units values (4, 'TB');
Run Code Online (Sandbox Code Playgroud)

编辑: SQL小提琴这里的问题