我觸發此查詢問題在活動記錄順序條款和限制
p "my query starts here..."
@relevant_customers_for_total_spent = Customer.order("total_amount DESC").where('id IN (?)',@customers_ids).limit(relevant_customers_count_for_total_spent)
p " ------- "
p relevant_customers_count_for_total_spent # output is: 1139
p @relevant_customers_for_total_spent.count # output is: 2888
p " ------- "
更在日誌中說,實際的查詢解僱是:
SELECT COUNT(*) FROM `customers` WHERE (id IN (2,3,4,5,6,75,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,75,296,297,298,2889)) LIMIT 1139
所以問題是:
- 爲什麼在實際查詢中沒有訂單子句?
- 爲什麼@ relevant_customers_for_total_spent.count大於relevant_customers_count_for_total_spent。它應該等於或小於。
* 更新-1 *
我得到了第二個問題:
@relevant_customers_for_total_spent.length
是計算元素數量的正確方法。
更新 - 2
我有一些客戶ID陣列中的類似[2,3,4,5,6,75,56,57,58,59,60,61,62] 。我在Customer模型中有一個屬性,即total_amount。我想按照total_amount(DESC)的順序重新列出所有客戶ID。我有另一個因素,它指定了限制,即我從該列表中需要多少個客戶。有些東西,如果它的5。所以我需要從總數的最高5個客戶。
我相信你會做BR不正確的查詢。你能解釋一下查詢背後的想法嗎? – gmile
'哪裏('ID IN(?)',@ customers_ids)' - 多麼醜陋的建築!使用'where(id:@customers_ids)'。如果你傳遞一個數組,那麼Rails會爲你創建'IN'。如果是單個值,它會生成'='子句。傳遞關係(如'Model.select(:id)')會給你嵌套的SQL查詢。 – jdoe