简体   繁体   English

SQL:如何使用 DISTINCT 保持行顺序?

[英]SQL: How to keep rows order with DISTINCT?

The following SQL query:以下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

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 :仅在我添加DISTINCT后获取每个id

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值改变了顺序:

id
---
429
443

What could be the reason for that?这可能是什么原因?

How could I keep the order?我怎样才能保持订单?

the distinct key word is doing what it's supposed to do, return one row each with a given column value. distinct的关键字正在做它应该做的事情,每行返回一个具有给定列值的行。 Distinct doesn't allow you to specify which such row will be returned, and it's clear from the original query that such an ordering is allowed (there is a row with id 443 that follows a row with id 429). Distinct 不允许您指定将返回哪个这样的行,并且从原始查询中可以清楚地看出允许这样的排序(有一个 id 为 443 的行跟在一个 id 为 429 的行之后)。

To take control of what rows will be returned, you need to reformulate the query.要控制将返回哪些行,您需要重新编写查询。 A typical solution I'll take is to use a group by , selecting the group column and the desired row from each group, something to the effect of我将采用的典型解决方案是使用group by ,从每个组中选择组列和所需的行,效果如下

SELECT message.id, MAX(message.created_at) FROM message GROUP BY message.id;

If I need to do more, I'll use this sort of query as a subselect in a larger query, possibly joining on the id field to get more fields from the preferred row, Or ordering the query in a particular way.如果我需要做更多,我将使用这种查询作为更大查询中的子选择,可能加入 id 字段以从首选行获取更多字段,或者以特定方式对查询进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM