SELECT `t`.`id_thing`, `t`.`data`, JSON_ARRAYAGG(`n`.`note`) AS `all_notes`
FROM `things` AS `t`
LEFT JOIN `notes` AS `n` ON `n`.`id_thing` = `t`.`id_thing`
GROUP BY `t`.`id_thing`, `t`.`data`
WITH `cte` AS (
SELECT *, ROW_NUMBER() OVER `w` AS `row_num`
FROM `table`
WHERE `size` <= :size
WINDOW `w` AS (
PARTITION BY `size`
ORDER BY `date` DESC
)
) SELECT *
FROM `cte`
WHERE `row_num` = 1
ORDER BY `price` = 0, `size` DESC
LIMIT 1
SELECT `t`.*
FROM (
SELECT `size`, MAX(`date`) as `date`
FROM `table`
WHERE `size` <= 32
GROUP BY `size`
) AS `m`
JOIN `table` AS `t`
ON `t`.`size` = `m`.`size` AND `t`.`date` = `m`.`date`
ORDER BY `t`.`price` = 0, `t`.`size` DESC
LIMIT 1