【发布时间】:2017-09-01 17:00:46
【问题描述】:
我正在使用带有 PostGres 9.5 的 Rails 5。我有一张跟踪价格的表格...
Table "public.crypto_prices"
Column | Type | Modifiers
--------------------+-----------------------------+------------------------------------------------------------
id | integer | not null default nextval('crypto_prices_id_seq'::regclass)
crypto_currency_id | integer |
market_cap_usd | bigint |
total_supply | bigint |
last_updated | timestamp without time zone |
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
我想获得选定货币的每种货币的最新价格(last_updated 最高)。我可以找到与某些货币相关的所有价格,像这样
current_prices = CryptoPrice.where(crypto_currency_id: CryptoIndexCurrency.all.pluck(:crypto_currency_id).uniq)
然后我可以按货币将它们排序到数组中,循环遍历每个数组,直到找到具有最大 last_updated 值的那个,但是 我怎样才能编写一个查找器,它会准确地返回每种货币中最大的一行last_updated 日期?
编辑:像这样尝试了 Owl Max 的建议
ids = CryptoIndexCurrency.all.pluck(:crypto_currency_id).uniq
crypto_price_ids = CryptoPrice.where(crypto_currency_id: ids).group(:crypto_currency_id).maximum(:last_updated).keys
puts "price ids: #{crypto_price_ids.length}"
@crypto_prices = CryptoPrice.where(crypto_currency_id: crypto_price_ids)
puts "ids: #{@crypto_prices.size}"
虽然第一个“puts”只显示了“12”的大小,但第二个 put 显示了超过 38,000 个结果。它应该只返回 12 个结果,每种货币一个。
【问题讨论】:
-
只是抛出一个想法-您是否考虑过按`last_updated`排序并抢占第一个实例?
-
那只会返回一个结果,不是吗?
-
如果你想要多个,你可以用
.first(3)for 3 做类似的事情(随便填什么数字)。 -
我不是这个意思。我只知道某些货币的每种货币的最新价格(例如我指定的 crypto_currency_id 值)。我应该在哪里使用“first(3)”指定特定的 ID?
标签: ruby-on-rails postgresql ruby-on-rails-5