Rails选择查询奇怪的行为

时间:2015-09-14 19:19:48

标签: sql ruby-on-rails activerecord

我有一个带有has_many:domains的模型服务器。我想按域名排序我的结果,我不想使用cache_count。所以我喜欢

@servers = @servers.joins(:domains).select('servers.*, COUNT(domains.id) AS domains_count').group('servers.id').reorder('domains_count ASC'))

我有一个错误no such column: domains_count。所以我检查日志中的SQL并变得非常惊讶

SELECT  COUNT(*) AS count_all, servers.id AS servers_id FROM "servers" INNER JOIN "domains" ON "domains"."server_id" = "servers"."id" GROUP BY servers.id  ORDER BY domains_count ASC

为什么会这样?我该怎么做才能使我的查询有效?

感谢。

UPD:我错了一点。这个奇怪的count_all是在@servers.size上生成的(仍然是为什么?)。不过我还有

SELECT  servers.*, COUNT(domains.id) AS domains_count FROM "servers" INNER JOIN "domains" ON "domains"."server_id" = "servers"."id" GROUP BY servers.id  ORDER BY domains_count ASC

总是只生成一条记录。

1 个答案:

答案 0 :(得分:0)

您在order by中有一列我猜是计算列count(domains.id)。由于您无法使用之前定义的alias,因此您应该使用实际计算。

SELECT COUNT(domains.id) AS domains_count, servers.id
FROM "servers" INNER JOIN "domains" 
ON "domains"."server_id" = "servers"."id" 
GROUP BY servers.id 
order by COUNT(domains.id) 
--  ORDER BY domains_count ASC --remove this or use an appropriate column,   
-- guessing the ordering should be based on count(*)