Для этого можно использовать агрегацию, если deleted
принимает только значения 0 и 1:
SELECT activityKey, editDate,
(CASE WHEN MAX(CASE WHEN deleted = 0 THEN editDate END) = MAX(editDate)
THEN 0 ELSE 1
END) as deleted
FROM (SELECT activityKey, editDate, deleted
FROM activities
WHERE projectID = '4' AND deleted = 0
UNION ALL
SELECT activityKey, editDate, deleted
FROM edited
WHERE projectID = '4'
) ae
GROUP BY activityKey
ORDER BY MAX(editDate) DESC
LIMIT 20 OFFSET 0;
Более общее решение заключается в использовании ROW_NUMBER()
, но в этом случае это работает .
РЕДАКТИРОВАНИЕ:
Если вы хотите пропустить строки с deleted
= 1, добавьте предложение HAVING
:
SELECT activityKey, editDate,
(CASE WHEN MAX(CASE WHEN deleted = 0 THEN editDate END) = MAX(editDate)
THEN 0 ELSE 1
END) as deleted
FROM (SELECT activityKey, editDate, deleted
FROM activities
WHERE projectID = '4' AND deleted = 0
UNION ALL
SELECT activityKey, editDate, deleted
FROM edited
WHERE projectID = '4'
) ae
GROUP BY activityKey
HAVING MAX(editDate) = MAX(CASE WHEN deleted = 1 THEN editDate END)
ORDER BY MAX(editDate) DESC
LIMIT 20 OFFSET 0;