{
"id": 1,
"price": {
"type": 1,
"price_b": 100,
"price_c": 80,
"price_d": 20
},
}
SELECT d.id, name, p.type, pp.price_b, pp.price_c, pp.price_d FROM device d
INNER JOIN (SELECT device_id, MAX(type) as "type" FROM price GROUP BY device_id) p ON p.device_id = d.id
INNER JOIN price pp ON pp.type = p.type AND pp.device_id = d.id
SELECT d.id,
CASE
WHEN p3.type IS NOT NULL THEN p3.type
WHEN p2.type IS NOT NULL THEN p2.type
WHEN p1.type IS NOT NULL THEN p1.type
END AS type,
CASE
WHEN p3.type IS NOT NULL THEN p3.price_b
WHEN p2.type IS NOT NULL THEN p2.price_b
WHEN p1.type IS NOT NULL THEN p1.price_b
END AS price_b,
CASE
WHEN p3.type IS NOT NULL THEN p3.price_c
WHEN p2.type IS NOT NULL THEN p2.price_c
WHEN p1.type IS NOT NULL THEN p1.price_c
END AS price_c,
CASE
WHEN p3.type IS NOT NULL THEN p3.price_d
WHEN p2.type IS NOT NULL THEN p2.price_d
WHEN p1.type IS NOT NULL THEN p1.price_d
END AS price_d
FROM device d
LEFT JOIN (SELECT device_id, type, price_b, price_c, price_d
FROM price WHERE type = 3) p3 ON d.id = p3.device_id
LEFT JOIN (SELECT device_id, type, price_b, price_c, price_d
FROM price WHERE type = 2) p2 ON d.id = p2.device_id
LEFT JOIN (SELECT device_id, type, price_b, price_c, price_d
FROM price WHERE type = 1) p1 ON d.id = p1.device_id