我刚遇到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
答案 0 :(得分:0)
看起来.last
将ASC 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>