我如何將它翻譯成 ruby?? on rails 語法?
@products = Product.select('* FROM products p inner join (SELECT product_id, AVG(rating) as avg_rating
FROM reviews GROUP BY product_id) as x on p.id = x.product_id ORDER BY x.avg_rating DESC')
錯誤:從“第 2 行:...在 p.id = x.product_id ORDER BY x.avg_rating DESC 從“產品... ^
uj5u.com熱心網友回復:
您可以像這樣使用子查詢:
Product.joins(
"INNER JOIN (#{Review.select('product_id, AVG(rating) AS avg_rating').group('product_id').to_sql}) AS reviews ON reviews.product_id = products.id"
).order('reviews.avg_rating DESC')
或者你可以使用Arel
products = Product.arel_table
reviews = Review.arel_table
subquery = reviews.project(:product_id, reviews[:rating].average).group(:product_id).as('reviews')
products.join(subquery).on(subquery[:product_id].eq(products[:id])).order(reviews[:rating].average.desc)
uj5u.com熱心網友回復:
你可以試試下面:
Product.joins("INNER JOIN ((SELECT product_id, AVG(rating) as avg_rating FROM reviews GROUP BY product_id) as x on products.id = x.product_id)")
.order("x.avg_rating DESC")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489091.html
