当存在多个left_joins时,查询将忽略顺序

时间:2018-11-15 19:04:56

标签: sql ruby-on-rails postgresql activerecord

我正在尝试按Posts表示的转化率订购unique commenters/impressions。我拥有的查询进行了计算,但是通过该计算进行排序失败。在调查之后,即使查询相同,order似乎在我联接两个表时也会中断。这是一个最小的示例:

# Works as expected
Post.left_joins(:impressions)
  .group(:id)
  .order("count(impressions) DESC")

# Orders seemingly randomly
Post.left_joins(:comments, :impressions)
  .group(:id)
  .order("count(impressions) DESC")

这是从这些查询生成的SQL:

-- Works as expected
SELECT "posts".* FROM "posts" 
  LEFT OUTER JOIN "impressions" ON "impressions"."post_id" = "posts"."id" 
  GROUP BY "posts"."id" 
  ORDER BY count(impressions) DESC

-- Seemingly random order
SELECT "posts".* FROM "posts" 
  LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" 
  LEFT OUTER JOIN "impressions" ON "impressions"."post_id" = "posts"."id" 
  GROUP BY "posts"."id" 
  ORDER BY count(impressions) DESC

我正在使用Postgres和Rails 5.2


实际上,查询将更像这样:

Post.left_joins(:comments, :impressions)
  .group(:id)
  .order("cast(count(distinct(comments.user_id)) AS float) / cast(greatest(count(impressions), 1) AS float) DESC")

但是,最小的示例显示了我所看到的不直观的行为。


这是预期的吗?如果是这样,如何解决?

0 个答案:

没有答案