2

我要做的只是按过去 7 天的印象数(当有人查看帖子时创建印象)对帖子进行排序。这是我的命名范围

scope :popular_last_week, unscoped
    .select("websites.*, COUNT(impressions.id) AS counted_impressions")
    .joins("INNER JOIN impressions ON websites.id = impressions.impressionable_id")
    .where("impressions.created_at >= ?", 7.days.ago)
    .where(:is_published => true)
    .group("websites.id")
    .order("counted_impressions DESC")

(“counted_impressions”用于避免发布记录冲突)

然而,这会产生以下无效 SQL(counted_impressions 不是有效列):

SELECT COUNT(*) AS count_all, websites.id AS websites_id FROM "websites" INNER JOIN impressions ON websites.id = impressions.impressionable_id WHERE "websites"."is_published" = 't' AND (impressions.created_at >= '2013-01-11 17:48:03.954542') GROUP BY websites.id ORDER BY counted_impressions

似乎选择语句被忽略了。我哪里出错了,或者我应该怎么做才能使 SQL 语句为:

SELECT websites.*, COUNT(impressions.id) AS counted_impressions FROM "websites" INNER JOIN impressions ON websites.id = impressions.impressionable_id WHERE "websites"."is_published" = 't' AND (impressions.created_at >= '2013-01-11 17:42:57.771777') GROUP BY websites.id ORDER BY counted_impressions DESC

4

2 回答 2

0

尝试这个:

  范围:popular_last_week,无范围
    .select(arel_table[Arel.star])
    .select(Website.arel_table[:id].count.as("counted_impressions"))
    .joins("INNER JOIN 在网站上的印象.id = 印象.impressionable_id")
    .where("impressions.created_at >= ?", 7.days.ago)
    .where(:is_published => true)
    .group("websites.id")
    .order("counted_impressions DESC")
于 2013-01-19T00:05:53.477 回答
0

似乎查询应该是:

SELECT count(*) AS impression_count, w.id AS website_id 
FROM websites as w
INNER JOIN impressions as i ON w.id = i.impressionable_id 
WHERE w.is_published = 't' AND i.created_at >= '2013-01-11 17:48:03.954542'
GROUP BY w.id 
ORDER BY impression_count DESC;

似乎您可以跳过此查询中的联接,然后对下一个查询运行“is_published”检查以获取实际的帖子数据...假设您仅使用此查询来获取第二个查询的 ID 列表获取数据。

于 2013-01-19T02:40:59.873 回答