【发布时间】:2016-02-15 23:34:53
【问题描述】:
我正在努力寻找解决问题的有效方法:
我需要查找表中的所有行,其中另一行具有相反的列值。
例如,我有包含 id 和 amount 列的交易
| id | amount |
|----|--------|
| 1 | 1 |
| 2 | -1 |
| 3 | 2 |
| 4 | -2 |
| 5 | 3 |
| 6 | 4 |
| 7 | 5 |
| 8 | 6 |
查询应该只返回前 4 行:
| id | amount |
|----|--------|
| 1 | 1 |
| 2 | -1 |
| 3 | 2 |
| 4 | -2 |
我目前的解决方案非常高效,因为我正在处理 1000 笔交易:
transactions.find_each do |transaction|
unless transactions.where("amount = #{transaction.amount * -1}").count > 0
transactions = transactions.where.not(amount: transaction.amount).order("@ amount DESC")
end
end
transactions
是否有任何内置的 Rails 或 Postgresql 函数可以帮助解决这个问题?
【问题讨论】:
-
我是新手。但我不明白你为什么选择前 4 行。你能解释一下吗?
-
@Maxence 这 4 行中的每一行在表中都有另一行具有相反的值。例如,
-1与1相反。 -
你不需要明确地配对它们吗?只是把它们作为一批? (假设 10 行的值为 1,45 行的值为 -1,你想要 55 行加在一起吗?)
-
@Maxence 是的,这就是我需要的。
-
尝试找到唯一值。像 transactions.abs.uniq (我是菜鸟,但这似乎是很好的逻辑)。不确定是否可以工作,因为 uniq 似乎只在数组上工作.. 也检查这个帖子stackoverflow.com/questions/9658881/…
标签: ruby-on-rails postgresql ruby-on-rails-4