我想知道是否可以使用像这样的Rails Active Record帮助程序编写非常复杂的SQL(数字稍后会被变量替换):
SELECT
photographs.id,
(COUNT(distinct comments.id) / 50.0 * 100 * 0.25) + (15 * 0.1) + (COUNT(distinct likes.id) / 100.0 * 100 * 0.05) +(COUNT(distinct likes.id) / COUNT(distinct views.id) * 100 * 0.4) +(COUNT(distinct likes.id) * 2.4 / 100.0 * 0.2) AS FINAL_RANKING
FROM photographs
INNER JOIN comments
ON photographs.id = comments.photograph_id
INNER JOIN likes
ON photographs.id = likes.photograph_id
INNER JOIN views
ON photographs.id = views.photograph_id
GROUP BY photographs.id
ORDER by FINAL_RANKING DESC;
我在Rails doc上找到了更简单的例子或简单的多内连接但没有计数
答案 0 :(得分:1)
Rails在select
命令中接受SQL。
请参阅Active Record Query Interface | Selecting Specific Fields
这样的事情对你有用:
Photographs.joins(:comments, :likes, :views, :users).where(
"users.id = 1").select("COUNT(whatever)")
无法保证实际运行。