有一个Company
模型,其中包含total_standard_score
列和code
列。
该公司有很多share_holders
。该模型具有pagination
。
scope :share_holder, -> name {
joins(:share_holders).where("share_holders.name LIKE '%#{name}%'") if name.present?
}
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"
答案 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;
这不应该有任何解析问题,也应该更有效率。