MySQL语法错误:ORDER BY子句不在GROUP BY中

时间:2017-04-27 12:40:33

标签: php mysql laravel eloquent

我有一个查询,我想通过shipping_date订购,但我收到此错误:

QueryException in Connection.php line 770:
    SQLSTATE[42000]: Syntax error or access violation: 1055 Expression 1 of 
    ORDER BY clause is not in GROUP BY clause and contains nonaggregated 
    column 'device.devices.shipping_date' which is not functionally 
    dependent on columns in GROUP BY clause; this is incompatible with 
    sql_mode=only_full_group_by (SQL: select count(*) as device, 
    DATE_FORMAT(shipping_date,"%M %Y") as year from `devices` where 
    `shipping_date` is not null and `internal_use` = 0 group by `year` order by `shipping_date` asc)

我的代码:

$sold_devices = Device::selectRaw('count(*) as device, DATE_FORMAT(shipping_date,"%M %Y") as year')
                 ->whereNotNull('shipping_date')
                 ->where('internal_use', '=', 0)
                 ->groupBy('year')
                 ->orderBy('shipping_date', 'asc')
                 ->pluck('device', 'year');

任何帮助?

由于

2 个答案:

答案 0 :(得分:1)

您必须在select中指定确切的group by列:在您的情况下

->groupBy('DATE_FORMAT(shipping_date,"%M %Y")')
->orderBy('DATE_FORMAT(shipping_date,"%M %Y")', 'asc')

一般来说,您不能在wheregroup byorder by子句中使用列别名。

修改

要更改订购标准,您可以使用月份的数值而不是其名称:

->groupBy('DATE_FORMAT(shipping_date,"%M %Y")')
->orderBy('DATE_FORMAT(shipping_date,"%Y%c")', 'asc')

答案 1 :(得分:0)

让我们试一试。

它会起作用......

 ->groupBy(DB::raw('DATE_FORMAT(shipping_date,"%M %Y")'))
   ->orderBy(DB::raw('DATE_FORMAT(shipping_date,"%M %Y"))','asc')