我怀疑我继承了一些糟糕的 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 |
+------+--------------+
这是我希望能够产生的:
+----+---------+---------+---------+
| id | total_1 | total_2 | total_3 |
+----+---------+---------+---------+
| 1 | 128GB | 128GB | 6TB |
| 2 | 1TB | 12GB8 | 2TB |
| 3 | 100GB | 100GB | 100GB |
+----+---------+---------+---------+
user_space 表中的最后 3 个“units_s*”列与 space_units 表中的“type”列相关。
任何人都可以帮我进行合适的查询吗?我已经在这里工作了很长时间,无法弄清楚。不幸的是,我不允许删除表格并正确实现它们。
最佳答案
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 |
+----+---------+---------+---------+
编辑:使用 Format text as a table格式化输出
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');
关于mysql - 在坏表上加入 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324002/