SQL - 数据库 table 映射器 - 插入 table,基于 select 并连接

SQL - Database table mapper - Insert into table, based on select and joins

这是问题的生活示例,因此您可以更好地理解我们需要什么。

示例

我们有 3 tables

cars
*id
*description

car_spec
*id
*car_id
*spec_id
*amount

specs
*id
*name

对于每个汽车项目,我们要保留这些数据:

*id
*description

和 3 'spec' 值位于 'specs' table,基于 'car_spec' table:

doors
pistons
hp

我们想像这样将所有需要的数据合并成一个table。

car_db
*id
*description
*original_car_id
*doors
*pistons
*hp

示例数据

汽车table

id | description
1  | 2020 car 1
2  | 2020 car 2
3  | 2020 car 3

car_spec table

id | car_id | spec_id | amount
1  | 1      | 1       | 2
2  | 1      | 2       | 12
3  | 1      | 3       | 550
4  | 2      | 1       | 4
5  | 2      | 2       | 4
6  | 2      | 3       | 250

规格table

id | name
1  | doors
2  | pistons
3  | hp

样本结果table

id | description | original_car_id | doors | pistons | hp
1  | 2020 car 1  | 1               | 2     | 12      | 550
2  | 2020 car 2  | 2               | 4     | 4       | 250
3  | 2020 car 3  | 3               | 4     | 8       | 400

我们需要什么

我们需要导出一个包含所需数据的新 table。

我们可以在 sql 中做到这一点吗? 如果没有,我们如何做有什么建议吗?

您通常会使用条件聚合来透视规范。以下语法应该适用于几乎所有数据库:

select c.id, 
    max(case when s.name = 'doors' then cs.amount end) as doors,
    max(case when s.name = 'pistons' then cs.amount end) as pistons,
    max(case when s.name = 'hp' then cs.amount end) as hp
from cars c
inner join car_spec cs on cs.car_id = c.id
inner join specs s on s.id = cs.spec_id
group by c.id

如果 'specs' table 是固定的你可以使用这样的子查询:

select c.id, c.description, c.id as original_car_id,
  (select d.amount from car_spec d where d.car_id = c.id and d.spec_id = 1) as doors,
  (select d.amount from car_spec d where d.car_id = c.id and d.spec_id = 2) as pistons,
  (select d.amount from car_spec d where d.car_id = c.id and d.spec_id = 3) as hp
from cars c;