Rails 3 Query: getting error while using 'select' with 'order'

允我心安 提交于 2019-12-21 21:26:20

问题


I was trying to answer this question where I got this issue.

I have a user model having id, email and first_name columns. So in single query I want to select users with distinct first_name, sort them by email and pluck their ID.

How can I do this?

what won't work:

  1. User.select(:first_name).uniq.pluck(:id)

    because it fires this SQL SELECT DISTINCT "users"."id" FROM "users". This is selecting distinct id from user. But we want to select distinct first_name

  2. User.order("email DESC").pluck(:id).uniq

    SQL generated: SELECT "users"."id" FROM "users" ORDER BY email DESC. This will not work because the sql generated is not checking for uniqueness of first_name.


回答1:


You could test the SQL with this SQLFIDDLE.

Only Sqlite and MySql support this usage, but others don't.

Refer to this postgresql document.

In the SQL-92 standard, an ORDER BY clause can only use result column names or numbers

It is also possible to use arbitrary expressions in the ORDER BY clause, including columns that do not appear in the SELECT result list. Thus the following statement is valid:

SELECT name FROM distributors ORDER BY code;

A limitation of this feature is that an ORDER BY clause applying to the result of a UNION, INTERSECT, or EXCEPT clause can only specify an output column name or number, not an expression.

For your case, there is no need of using uniq, all user id distinct already, so why don't you try this:

User.order("email DESC").pluck(:id)

Assuming the ids duplicated, you could uniq by ruby instead of DB.

User.order("email DESC").pluck(:id).uniq

This script will never generate sql with distinct. This uniq after pluck is an Array#uniq method.



来源:https://stackoverflow.com/questions/25616358/rails-3-query-getting-error-while-using-select-with-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!