如何解决“for SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中”错误

时间:2018-03-17 10:29:42

标签: sql ruby-on-rails

有一个Company模型,其中包含total_standard_score列和code列。 该公司有很多share_holders。该模型具有pagination

company.rb

scope :share_holder, -> name {
  joins(:share_holders).where("share_holders.name LIKE '%#{name}%'") if name.present?
}

companies_controller.rb

sort_string = "total_standard_score is null, total_standard_score desc, code asc"
Company.select('companies.*').share_holder('name').order(sort_string).distinct

此代码失败,错误为:for SELECT DISTINCT, ORDER BY expressions must appear in select list

我应该为total_standard_score is null, total_standard_score desc, code asc选择语句添加什么内容?

这是to_sql

的结果
"SELECT DISTINCT companies.* FROM \"companies\" INNER JOIN \"share_holders\" ON \"share_holders\".\"company_id\" = \"companies\".\"id\" WHERE (share_holders.name LIKE '%name%')  ORDER BY total_standard_score is null, total_standard_score desc, code asc"

1 个答案:

答案 0 :(得分:1)

根据您的描述,这是您的查询(以更易读的形式)

SELECT DISTINCT c.*
FROM companies c INNER JOIN
     share_holders sh
     ON sh.company_id = c.id
WHERE sh.name LIKE '%name%' 
ORDER BY c.total_standard_score is null, c.total_standard_score desc, c.code asc;

我怀疑问题是c.total_standard_score上的表达式。 不应该是是一个问题,但它可能是。

您的基础数据库可能支持NULLS LAST

ORDER BY c.total_standard_score desc nulls last, c.code asc;

但编写查询的更有效方法是使用EXISTS

SELECT c.*
FROM companies c 
WHERE EXISTS (SELECT 1
              FROM share_holders sh
              WHERE sh.company_id = c.id AND sh.name LIKE '%name%'
             ) 
ORDER BY c.total_standard_score is null, c.total_standard_score desc, c.code asc;

这不应该有任何解析问题,也应该更有效率。