0

我承认这是一个糟糕的标题,但我认为这应该澄清。假设我有一个看起来像这样的车辆表

Vehicles

| vehicle_id | vehicle_name | vehicle_price |
| 1          | pinto        | 70000         |

Vehicle Options 

| vehicle_id | option_name  | option_value  |
| 1          | color        | red           |
| 1          | engine       | v8            |

我怎样才能将所有这些作为一排恢复...基本上是附加选项的车辆排。

| vehicle_id = 1 | vehicle_name = pinto | option_value = red | option_value(renamed) = V8 |
4

1 回答 1

0

您想要PIVOTMySQL 没有默认功能的记录。但是您仍然可以使用MAX()andCASE语句手动执行此操作。

SELECT  a.vehicle_id,
        a.vehicle_name,
        a.vehicle_price,
        MAX(CASE WHEN option_name = 'color' THEN option_value END) color,
        MAX(CASE WHEN option_name = 'engine' THEN option_value END) engine
FROM    Vehicles a
        INNER JOIN VehicleOptions b
            ON a.vehicle_id = b.vehicle_id 
GROUP   BY  a.vehicle_id,
            a.vehicle_name,
            a.vehicle_price

输出

╔════════════╦══════════════╦═══════════════╦═══════╦════════╗
║ VEHICLE_ID ║ VEHICLE_NAME ║ VEHICLE_PRICE ║ COLOR ║ ENGINE ║
╠════════════╬══════════════╬═══════════════╬═══════╬════════╣
║          1 ║ pinto        ║         70000 ║ red   ║ v8     ║
╚════════════╩══════════════╩═══════════════╩═══════╩════════╝
于 2013-09-28T18:43:01.310 回答