在Rails中加入COALESCE和ORDER BY

时间:2015-03-19 17:50:48

标签: ruby-on-rails ruby-on-rails-3

我刚遇到Rails的问题,我在同一个查询中无法正确使用JOIN和多个ORDER BY(其中一个是COALESCE函数)。这是在SQL中是非法的(可疑)还是只是Rails实现的问题?另外,我该如何解决它?

# Works!
Post.joins(:author).order("COALESCE(title, '---') DESC")
=> SELECT  "posts".* FROM "posts" INNER JOIN "authors" ON "posts"."author_id" = "authors"."id" ORDER BY COALESCE(title DESC, '--')

# Fails - syntax error in SQL
Post.joins(:author).order("COALESCE(title, '---') DESC").last #last should automatically apply an ORDER BY id DESC;
=> SELECT  "posts".* FROM "posts" INNER JOIN "authors" ON "posts"."author_id" = "authors"."id" ORDER BY COALESCE(title DESC, '--') ASC LIMIT 1

2 个答案:

答案 0 :(得分:0)

看起来.lastASC LIMIT 1应用于SQL查询。这似乎混淆了rails语法解析器,它将DESC移动到一个奇怪的地方,这会导致错误。

SELECT "discussion_topics".* FROM "discussion_topics" ORDER BY COALESCE(title DESC, '---') ASC LIMIT 1

而不是

SELECT "discussion_topics".* FROM "discussion_topics" ORDER BY COALESCE(title, '---') DESC

您可以将DESC更改为ASC并安全使用.first

答案 1 :(得分:0)

我会尝试使用Postgres

Post.select(“ COALESCE(title,'---')DESC”)。joins(:author).order(“ COALESCE(title,'---')DESC”)。limit(1)< / p>