0
Ver 14.14 Distrib 5.1.73
活动记录(MYSQL) - 从多个列
activerecord (4.1.14)
我有属于贷款人和借款人交易模型选择不同的ID。我想在一个SQL查询中找到机构交易的所有uniq交易对手。以下作品中的查询,但只是因为我压扁&独特-IFY的SQL查询后的数组:
Trade.where("borrower_id = :id OR lender_id = :id", id: institution.id).uniq.pluck(:lender_id, :borrower_id).flatten.uniq
(我知道这包括机构本身的,所以我们用[1,2,3,4] - [1]
后恢复正常)
但什么我想要做的是使用Group By
子句或其他东西,以便我的SQL查询处理flatten.uniq
部分。
下面不起作用,因为它返回的独特组合lender_id
和borrower_id
一个嵌套的数组:
Trade.where("borrower_id = :id OR lender_id = :id", id: institution.id).group(:lender_id, :borrower_id).uniq.pluck(:lender_id, :borrower_id)
=> [[1,2], [1,3], [2,3]]
我只想唯一ID的平面阵列:[1,2,3]
任何想法?谢谢!
感谢回答。我正在使用一个GROUP BY,因为类似的SO帖子(http://stackoverflow.com/questions/12188027/mysql-select-distinct-multiple-columns?rq=1)....我开放给任何作品!话虽如此,你的查询会产生一个嵌套数组返回集,其中包含lender_id和borrower_id的唯一_combinations_(例如[[1,2],[1,3]])...我只需要唯一的ID作为平面数组(例如[1,2,3])。 – daino3
我会在应用程序中进行那种处理。 – Strawberry
大声笑,这就是我正在做的('flatten.uniq'),但我想了解如何通过SQL/ActiveRecord来做到这一点(因此问题)。似乎是一个非常相关/频繁的使用案例。 – daino3