【发布时间】:2014-03-29 03:25:29
【问题描述】:
我有一个这样的帖子表:
+-----+----------+------------+------------+
| id | topic_id | text | timestamp |
+-----+----------+------------+------------+
| 789 | 2 | foobar | 1396026357 |
| 790 | 2 | foobar | 1396026358 |
| 791 | 2 | foobar | 1396026359 |
| 792 | 3 | foobar | 1396026360 |
| 793 | 3 | foobar | 1396026361 |
+-----+----------+------------+------------+
如何按主题 id 对结果进行“分组”,同时提取最新记录(按时间戳降序排序)?
我了解到我可能不想要“group_by”,而是想要“distinct on”。我的 postgres 查询如下所示:
select distinct on (topic_id) topic_id, id, text, timestamp
from posts
order by topic_id desc, timestamp desc;
这很好用。但是,我不知道这是否是我可以在 DBIx::Class 中执行的操作,而无需编写自定义 ResultSource::View。我尝试了各种 group_by 与选择和列的安排,并尝试了 distinct => 1。如果/当返回结果时,它实际上并没有保留唯一性。
有没有办法通过结果集搜索来编写我正在尝试的查询,或者是否有更好的方法通过不同类型的查询来获得相同的结果?
【问题讨论】:
-
旁白:从不使用
text或timestamp等基本类型名称作为标识符。 -
感谢您的评论。有时某些事情是无法控制的,“从不”或“总是”做某事不是选择的问题。谢天谢地,我能够将 col 名称用双引号括起来。
标签: postgresql dbix-class