0

我想知道是否有可能使用 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 上找到了更简单的示例或简单的多重内连接,但没有计数

4

1 回答 1

1

Rails 在select命令中接受 SQL。

活动记录查询接口 | 选择特定字段

像这样的东西应该适合你:

Photographs.joins(:comments, :likes, :views, :users).where(
"users.id = 1").select("COUNT(whatever)")

不保证实际运行。

于 2013-07-01T20:15:15.070 回答