изменить таблицу в Мариадб - PullRequest
0 голосов
/ 26 октября 2018

Как мне изменить таблицу SQL (mariadb):

vehicle_id attr_id, attr_value
1   123 BMW
1   345 SERIES 3
1   678 manual

до:

vehicle_id, make, description, gearbox
1         , BMW , SERIES 3   , manual

Обычный:

SELECT vehicle_id, max(attr_value) FROM car_table group by vehicle_id;

vehicle_id, max(attr_value)
13086520180701  SERIES 3

и PIVOT не доступны (https://mariadb.com/kb/en/library/pivoting-in-mariadb/

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

Если значения attr_id всегда идентичны для make, description, gearbox, вы можете получить требуемый результат с помощью следующего запроса:

select make.vehicle_id  , 
make.attr_value as make ,
description.attr_value as description ,
gearbox.attr_value as gearbox 
from 
car_table make,  
car_table description, 
car_table gearbox 
where make.vehicle_id = description.vehicle_id 
and description.vehicle_id = gearbox.vehicle_id 
and make.attr_id = 123 
and description.attr_id = 345 
and gearbox.attr_id = 678 
0 голосов
/ 26 октября 2018

Вы можете попробовать использовать условное агрегирование

SELECT 
    vehicle_id, 
    max(case when attr_id=123 then attr_value) as make,
    max(case when attr_id=345 then attr_value) as description,
    max(case when attr_id=678 then attr_value) as gearbox
FROM car_table 
group by vehicle_id;
...