我有一个表 Device:
id | model | platform | quantity |
---|---|---|---|
1 | iphone7 | ios | 3 |
2 | iphone5 | ios | 2 |
3 | xiaomi4 | android | 2 |
4 | huawei | android | 1 |
我在 model 里加了个 scope 用来做 group 查询:
class Device
scope :stat, -> { select("model, platform, SUM(quantity) AS total").group("model, platform").order("total DESC") }
end
我在 controller 里调用:
class DevicesController < ApplicationController
def stat
@devices = Device.stat
end
end
但会出现错误:
Mysql2::Error: Unknown column 'total' in 'order clause': SELECT COUNT(*) AS count_all, model, platform AS model_platform FROM
devices
GROUP BY model, platform ORDER BY total DESC
就是说我的 scope 里的SUM(quantity) AS total
消失了。
我用rails console
打开,重新调用Device.stat
,发现又是正常的。
我把 scope 里的 order 去掉,log 中会输出如下两个信息:
(0.5ms) SELECT COUNT(*) AS count_all, device_model, platform AS model_platform FROM `device` GROUP BY model, platform
Device Load (0.3ms) SELECT model, platform, SUM(quantity) AS total FROM `devices` GROUP BY model, platform
感觉问题出在第一条语句上,为什么在 console 里会没有第一条语句,为什么第一条语句里会丢失 sum?