Stali jste se obětí laxních pravidel MySQL, která umožňují zahrnout neagregáty do dotazu GROUP BY. Jistě, pracujete s MIN nebo MAX a pouze ONE najednou, ale zvažte tento dotaz:
SELECT
CONCAT(work_type, work_id) AS condition_id,
status,
MIN(created_timestamp) as earliest,
MAX(created_timestamp) as latest
FROM conditions
GROUP BY condition_id
Nyní se zamyslete nad tím, který řádek sloupec stavu by měl pocházet z. Je absurdní dávat korelaci mezi agregované (ty ve GROUP BY) a neagregované sloupce.
Místo toho napište svůj dotaz takto
SELECT X.condition_id, C.status, X.earliest
FROM (
SELECT
CONCAT(work_type, work_id) AS condition_id,
status,
MIN(created_timestamp) as earliest
FROM conditions
GROUP BY condition_id
) X JOIN conditions C
on CONCAT(c.work_type, c.work_id) = X.condition_id
and c.created_timestamp = X.earliest
Ale pokud jste měli dva záznamy se stejným created_timestamp, bude to ještě složitější
SELECT X.condition_id, Max(C.status) status, X.earliest
FROM (
SELECT
CONCAT(work_type, work_id) AS condition_id,
status,
MIN(created_timestamp) as earliest
FROM conditions
GROUP BY condition_id
) X JOIN conditions C
on CONCAT(c.work_type, c.work_id) = X.condition_id
and c.created_timestamp = X.earliest
GROUP BY X.condition_id, X.earliest