我有一種情況,我只需要從特定的活動記錄查詢回應中獲取幾條記錄。
@annotations = Annotations.select('*', ROW_NUMBER() OVER (PARTITION BY column_a) ORDER BY column_b)
以上是@annotations我想對其應用以下邏輯的 Active Record 回應的查詢。有沒有更好的方法來以 rails 方式撰寫以下邏輯?
with some_table as
(
select *, row_number() over (partition by column_a order by column_b) rn
from the_table
)
select * from some_table
where (column_a = 'ABC' and rn <= 10) or (column_b <> 'AAA')
uj5u.com熱心網友回復:
ActiveRecord 在其高級 API 中不提供 CTE;但是使用一點 Arel,我們可以將其作為 FROM 子句中的子查詢
annotations_table = Annotation.arel_table
sub_query = annotations_table.project(
Arel.star,
Arel.sql('row_number() over (partition by column_a order by column_b)').as(:rn)
)
query = Arel::Nodes::As.new(sub_query, Arel.sql(annotations_table.name))
Annotation.from(query).where(
annotations_table[:column_a].eq('ABC').and(
annotations_table[:rn].lt(10)
).or(annotations_table[:column_b].not_eq('AAA'))
)
結果將是Annotation使用您的 CTE 和您描述的過濾器的物件集合。
查詢陳述句:
select annotations.*
from (
select *, row_number() over (partition by column_a order by column_b) AS rn
from annotations
) AS annotations
where (annotations.column_a = 'ABC' and annotations.rn <= 10) or (annotations.column_b <> 'AAA')
筆記:
通過一些額外的作業,我們可以將其設為 CTE,但在這種情況下似乎不需要
我們也可以使用一堆 hack 將其轉換
row_number() over (partition by column_a order by column_b)為 Arel,但這似乎與問題無關。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359527.html
