所以我设计了一个表格:
create_table "entries", :force => true do |t|
t.integer "id", :null => false, :autoincrement => true
t.text "text"
t.string "uuid"
t.datetime "created_at", :null => false
end
我有一个与“Database - data versioning in single table”类似的问题,除了我有多个源(其中一些可以离线工作)写入这个数据库,所以 current
位不能很好地工作对我来说。
我想知道获取每个 UUID 的最新信息的最佳方法是什么。
在 sqlite 中:SELECT "entries".* FROM "entries"GROUP BY uuid ORDER BY updated_at DESC
效果很好,但它在 postgres 中不是有效的语法,而且感觉有点简陋。有什么好的方法可以做到这一点,还是我需要重做我的模式?
最佳答案
获得所需结果的一种方法是使用 window function和一个派生表。 ActiveRecord 不理解其中任何一个,但总有 find_by_sql
:
Entry.find_by_sql(%q{
select id, text, uuid, created_at
from (
select id, text, uuid, created_at,
row_number() over (partition by uuid order by created_at desc) as r
from entries
) as dt
where r = 1
})
有趣的部分是:
row_number() over (partition by uuid order by created_at desc)
partition by uuid
类似于 group by uuid
但它不会折叠行,它只是修改 row_number()
窗口函数的行为使得 row_number()
是针对具有匹配 uuid
的行计算的; order by created_at desc
同样只适用于 row_number()
将查看的窗口。结果是 r = 1
剥离每组中的第一行。
关于ruby - 单表版本控制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11753576/