简体   繁体   English

在一列上变得与众不同,另一列排序

[英]Get distinct on one column, order by another

I'm building a messaging feature for an app, my database table looks like this: 我正在为应用程序构建消息传递功能,我的数据库表如下所示:

messages:
  id
  senderId
  receiverId
  threadId   <-- every message is part of a thread
  createdAt

I have a 'Messages' page which has a card for every message thread, but I want it to show the latest message in the card as a preview for each thread. 我有一个“消息”页面,其中每个消息线程都有一张卡片,但是我希望它在卡中显示最新消息作为每个线程的预览。 This is the query I've written so far: 这是我到目前为止编写的查询:

SELECT DISTINCT ON ("threadId") * FROM messages ORDER BY "createdAt" DESC;

So I'm doing DISTINCT ON ("threadId") , but I'm also selecting all the columns because I want all the data, that's why there's a * after the DISTINCT ON clause. 所以我在做DISTINCT ON ("threadId") ,但是我也选择了所有列,因为我想要所有数据,这就是为什么DISTINCT ON子句后面有一个* This query worked fine up until this point, but now it's failing on the ORDER BY clause. 到目前为止,该查询工作正常,但是现在在ORDER BY子句上失败了。 I want to return the message that was created last, but I'm getting an error: 我想返回上次创建的消息,但出现错误:

 ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("threadId") * FROM messages order by "cr... 

I understand the error I think (the ORDER BY column has to match the column that DISTINCT ON is being applied to) but I don't know how to get the query to be what I want, which is to be ordered by createdAt before it becomes distinct. 我理解我认为的错误( ORDER BY列必须与要应用DISTINCT ON的列匹配),但是我不知道如何使查询成为我想要的内容,该查询必须由createdAt对其进行排序变得与众不同。

Leading expressions in ORDER BY have to agree with expressions in DISTINCT ON : ORDER BY前导表达式必须与DISTINCT ON表达式一致:

SELECT DISTINCT ON ("threadId") *
FROM   messages
ORDER  BY "threadId", "createdAt" DESC;

Detailed explanation: 详细说明:


If you want to order results in a different way (like commented), you'll have to wrap the query in an outer query with a second ORDER BY . 如果要以不同的方式对结果进行排序(如注释),则必须使用第二个ORDER BY将查询包装在外部查询中。 See: 看到:

Or similar, depending on your exact situation and requirements. 或类似,取决于您的实际情况和要求。 There may be sophistication to get best results. 可能会有复杂性以获得最佳结果。 Recent example: 最近的例子:

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

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