Rails为复杂查询的计数生成无效的SQL

时间:2015-12-03 18:05:30

标签: ruby-on-rails activerecord

这是来自https://github.com/rails/rails/issues/22491

的转贴

鉴于此声明:

@items = DailyList.joins(:bar)
                              .select("daily_lists.*, (point(12, 34) <@> bars.coords) as bar_distance")
                              .order("bar_distance ASC")
                              .group('bars.id, daily_lists.id')
                              .limit(3)

它产生以下SQL:

SELECT  daily_lists.*, (point(12, 34) <@> bars.coords) bar_distance
FROM "daily_lists"
INNER JOIN "bars" ON "bars"."id" = "daily_lists"."bar_id"
GROUP BY bars.id, daily_lists.id 
ORDER BY bar_distance ASC
LIMIT 3

现在我们要检查一下我们有多少记录, @ items.count

SELECT  COUNT(daily_lists.*, (point(12, 34) <@> bars.coords) as bar_distance) AS count_daily_lists_all_point_12_34_bars_coords_as_bar_distance, bars.id, daily_lists.id AS bars_id_daily_lists_id
FROM "daily_lists"
INNER JOIN "bars" ON "bars"."id" = "daily_lists"."bar_id"
GROUP BY bars.id, daily_lists.id 
ORDER BY bar_distance ASC
LIMIT 3

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "as"
LINE 1: ...NT(daily_lists.*, (point(12, 34) <@> bars.coords) as bar_dis...

现在我尝试使用:全部作为解决方法, @ items.count(:all)

SELECT  COUNT(*) AS count_all, bars.id, daily_lists.id AS bars_id_daily_lists_id
FROM "daily_lists"
INNER JOIN "bars" ON "bars"."id" = "daily_lists"."bar_id"
GROUP BY bars.id, daily_lists.id 
ORDER BY bar_distance ASC
LIMIT 3

PG::UndefinedColumn: ERROR:  column "bar_distance" does not exist

伙计们......该怎么办?

1 个答案:

答案 0 :(得分:0)

&#34; as bar_distance&#34;我想是问题所在。你不能在计数中别名。

@items = DailyList.joins(:bar)
                  .select("daily_lists.*, (point(12, 34) <@> bars.coords) as bar_distance")
                  .order("bar_distance ASC")
                  .group('bars.id, daily_lists.id')
                  .limit(3)

@item_count = DailyList.joins(:bar)
                       .select("daily_lists.*, (point(12, 34) <@> bars.coords)")
                       .group('bars.id, daily_lists.id')
                       .limit(3)
                       .count