我承认这是一个糟糕的头衔,但我认为这应该澄清。假设我有一张类似于此的车辆表
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 |
答案 0 :(得分:0)
你希望PIVOT
MySQL没有默认功能的记录。但您仍然可以使用MAX()
和CASE
声明手动执行此操作。
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 ║
╚════════════╩══════════════╩═══════════════╩═══════╩════════╝