我有一个这样的posts表:
+-----+----------+------------+------------+
| 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::类中是否可以这样做,而不必编写自定义的ResultSource::View。我尝试过使用selects和columns的不同的group_by排列方式,也尝试过distinct => 1。如果/当返回一个结果时,它实际上不会保持唯一性。
有没有一种方法可以通过结果集搜索来编写我正在尝试的查询,或者是否有更好的方法来通过不同类型的查询获得相同的结果?
发布于 2014-03-29 02:24:55
请查看grouping results上的DBIC Cookbook中的部分。
我相信你想要的是类似这样的东西:
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"} ],
})当然,可以根据需要使用适当的聚合函数。
https://stackoverflow.com/questions/22719372
复制相似问题