gpt4 book ai didi

postgresql - group_by 或与 postgres/dbix-class 不同

转载 作者:行者123 更新时间:2023-11-29 13:31:13 25 4
gpt4 key购买 nike

我有一个这样的帖子表:

+-----+----------+------------+------------+
| 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“分组”结果,同时提取最新记录(按时间戳 desc 排序)?

我了解到我可能不需要“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。如果/当返回结果时,它实际上并没有保留唯一性。

有没有办法通过结果集搜索编写我正在尝试的查询,或者是否有更好的方法通过不同类型的查询获得相同的结果?

最佳答案

查看 DBIC Cookbook 中关于 grouping results 的部分.

我相信你想要的是类似这样的东西:

my $rs = $base_posts_rs->search(undef, {
columns => [ {topic_id=>"topic_id"}, {text=>"text"}, {timestamp=>"timestamp"} ],
group_by => ["topic_id"],
order_by => [ {-desc=>"topic_id"}, {-desc=>"timestamp"} ],
})

编辑:绕过严格的 SQL 分组的一种快速而肮脏的方法是这样的:

my $rs = $base_posts_rs->search(undef, {
columns => [
{ topic_id => \"MAX(topic_id)" },
{ text => \"MAX(text)" },
{ timestamp => \"MAX(timestamp)" },
],
group_by => ["topic_id"],
order_by => [ {-desc=>"topic_id"}, {-desc=>"timestamp"} ],
})

当然,根据您的需要使用适当的聚合函数。

关于postgresql - group_by 或与 postgres/dbix-class 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22719372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com