The following SQL query:
SELECT messages.id, messages.created_at, comments.created_at FROM messages
LEFT JOIN comments ON comments.message_id = messages.id
WHERE (messages.id IN (429,443))
ORDER BY GREATEST(messages.created_at, comments.created_at) DESC
returns:
id messages.created_at comments.created_at
--------------------------------------------------------
443 2 5
429 1 4
443 2 3
(I replaced dates with numbers for readability)
To get each id
only once I added DISTINCT
:
SELECT DISTINCT messages.id FROM messages
LEFT JOIN comments ON comments.message_id = messages.id
WHERE (messages.id IN (429,443))
ORDER BY GREATEST(messages.created_at, comments.created_at) DESC
But, in the result the id
values changed order:
id
---
429
443
What could be the reason for that ?
How could I keep the order ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…