URL PARAMを使用してSQLクエリで並べ替えます
-
11-12-2019 - |
質問
私は以下の巨大な醜いクエリを持っています、それはカタログビューでそれによって並べ替えたいです。
.select 100 - round((current_price / item.estimated_price)*100) as percent, item.cached_thumbnail_url, item.item_id, it.name,
ci.current_price, ci.close_date
from item
join catalog_item ci on ci.item_id = item.item_id
join item_translations as it on (it.item_id = item.item_id)
where (100 - round((current_price / item.estimated_price)*100)) > 49 and
item.estimated_price > 0 and ci.current_price > 0 and ci.close_date > now() and item.active = 1 and ci.active = 1 and
(current_price / estimated_price) < 1
order by (ci.close_date < DATE_ADD(now(), INTERVAL 17 hour)) and (item.estimated_price - current_price) desc
limit 12
解決
これがRORにどのように関連している可能性があるかどうかはわからない:
-
あなたはあなたのSELECT句に
100 - round((current_price / item.estimated_price)*100) as percent
を持っています。とにかく条件で同じ式を使用しています。 -
item.estimated_price
はゼロより小さいですか?item.estimated_price > 0
状態がゼロであれば、(100 - round((current_price / item.estimated_price)*100)) > 49
状態が誤っている場合はfalse になります。 -
(current_price / estimated_price) < 1
は同じ理由で過度のものですだからあなたはこのような照会をもう少し明確に書き換えることができます:
.select (100 - round((current_price / item.estimated_price)*100)) as percent, item.cached_thumbnail_url, item.item_id, it.name, ci.current_price, ci.close_date from item join catalog_item ci on ci.item_id = item.item_id join item_translations as it on (it.item_id = item.item_id) where percent > 49 and ci.current_price > 0 and ci.close_date > now() and item.active = 1 and ci.active = 1 order by (ci.close_date < DATE_ADD(now(), INTERVAL 17 hour)) and (item.estimated_price - current_price) desc limit 12
これは多くの状況をよく向上させませんが、私はあなたのDBアーキテクチャについてのもう一度理由を知らずにもっと言うことはできません。
BTWあなたの質問のリンクは機能しません(それは明らかにあなたのローカルリンクです)
他のヒント
BinaryCodeの答えを把握するには、arelでクエリをラップしてから、コントローラのアクションで、パラメータハッシュで渡されたフィールド上で順番に注文することができます。
class ItemsController < ApplicationController
...
def index
@items = Item.select(%{(100 - round((current_price / item.estimated_price)*100)) as percent,
item.cached_thumbnail_url, item.item_id, it.name,
ci.current_price, ci.close_date}).
joins('join catalog_item ci on ci.item_id = item.item_id').
joins('join item_translations as it on (it.item_id = item.item_id)').
where('percent > 49 and ci.current_price > 0 and ci.close_date > now() and item.active = 1 and ci.active = 1').
order(%{(ci.close_date < DATE_ADD(now(), INTERVAL 17 hour))
and (item.estimated_price - current_price) desc)}).limit(12)
@items = @items.order(params[:order]) if params[:order]
...
end
.
編集
下記のBinaryCodeとして、おそらくItem
モデルのメソッドにメインクエリを移動してコントローラコードクリーナーを作成し、まだそれからRelation
オブジェクトを返すようにしてください。現在のステートメントは、後で追加のorder
をチェーンすることができます。
.def index
@items = Item.by_price_ratio
@items = @items.order(params[:order]) if params[:order]
end