我希望在 Rails 中運行以下查詢(我使用 scuttle.io 站點將我的 SQL 轉換為對 rails 友好的語法):
這是原始查詢:
SELECT pools.name AS "Pool Name", COUNT(DISTINCT stakings.user_id) AS "Total Number of Users Per Pool" from stakings
INNER JOIN pools ON stakings.pool_id = pools.id
INNER JOIN users ON users.id = stakings.user_id
INNER JOIN countries ON countries.code = users.country
WHERE countries.kyc_flow = 1
GROUP BY (pools.name);
這是 scuttle.io 查詢:
<%Staking.select(
[
Pool.arel_table[:name].as('Pool_Name'), Staking.arel_table[:user_id].count.as('Total_Number_of_Users_Per_Pool')
]
).where(Country.arel_table[:kyc_flow].eq(1)).joins(
Staking.arel_table.join(Pool.arel_table).on(
Staking.arel_table[:pool_id].eq(Pool.arel_table[:id])
).join_sources
).joins(
Staking.arel_table.join(User.arel_table).on(
User.arel_table[:id].eq(Staking.arel_table[:user_id])
).join_sources
).joins(
Staking.arel_table.join(Country.arel_table).on(
Country.arel_table[:code].eq(User.arel_table[:country])
).join_sources
).group(Pool.arel_table[:name]).each do |x|%>
<p><%=x.Pool_Name%><p>
<p><%=x.Total_Number_of_Users_Per_Pool%>
<%end%>
現在,您可能會注意到,sctuttle.io 不包含我需要的 distinct 引數。我怎么能在這里使用 distinct 而不會出現諸如“Arel Node 不存在不同的方法”之類的錯誤?還是只是語法錯誤?
有沒有辦法使用 rails ActiveRecord 撰寫上述查詢?我確定有,但我真的不確定如何。
uj5u.com熱心網友回復:
答案
類Arel::Nodes::Count(an Arel::Nodes::Function) 接受一個布林值來表示區別。
def initialize expr, distinct = false, aliaz = nil
super(expr, aliaz)
@distinct = distinct
end
運算式是相同的#count快捷方式,也接受單個引數
def count distinct = false
Nodes::Count.new [self], distinct
end
因此,在您的情況下,您可以使用以下任一選項
Arel::Nodes::Count.new([Staking.arel_table[:user_id]],true,'Total_Number_of_Users_Per_Pool')
# OR
Staking.arel_table[:user_id].count(true).as('Total_Number_of_Users_Per_Pool')
建議1:您擁有的Arel似乎有點矯枉過正。鑒于自然關系,您應該能夠稍微簡化一下,例如
country_table = Country.arel_table
Staking
.joins(:pools,:users)
.joins( Arel::Nodes::InnerJoin(
country_table,
country_table.create_on(country_table[:code].eq(User.arel_table[:country])))
.select(
Pool.arel_table[:name]
Staking.arel_table[:user_id].count(true).as('Total_Number_of_Users_Per_Pool')
)
.where(countries: {kyc_flow: 1})
.group(Pool.arel_table[:name])
建議 2:將此查詢移至您的控制器。該視圖沒有進行資料庫呼叫的業務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478516.html
