我继承了我怀疑是一些糟糕的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”列相关。
有人可以帮我一个合适的查询吗?我现在已经多年了,无法弄明白。不幸的是,我不允许丢弃表格并正确实施它们。
答案 0 :(得分: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 |
+----+---------+---------+---------+
编辑:使用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');