以下 SQL 查询:
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
返回:
id messages.created_at comments.created_at
--------------------------------------------------------
443 2 5
429 1 4
443 2 3
(I replaced dates with numbers for readability)
只有在添加
id
后才能获得每个 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
但是,结果中
id
值改变了顺序:
id
---
429
443
这可能是什么原因?
如何保留订单?
distinct
关键字正在做它应该做的事情,每行返回一个给定的列值。 Distinct 不允许您指定将返回这样的行,并且从原始查询中可以清楚地看出,允许这样的排序(id 为 443 的行后面有 id 为 429 的行)。
要控制将返回哪些行,您需要重新构造查询。我采取的典型解决方案是使用 group by
,从每个组中选择组列和所需的行,从而达到
的效果
SELECT message.id, MAX(message.created_at) FROM message GROUP BY message.id;
如果我需要做更多的事情,我将使用这种查询作为较大查询中的子选择,可能会加入 id 字段以从首选行中获取更多字段,或者以特定方式对查询进行排序。
ORDER BY GREATEST(messages.created_at, comments.created_at) DESC
您正在按 GREATEST 的输出降序排序。 id 443 为 5,id 429 为 4。因此您的顺序是这样的。
如果您想维持订单,请删除
DESC
关键字