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

问题描述:

我有一个查询,我想通过SHIPPING_DATE订购,但我得到这个错误:MySQL的语法错误:ORDER BY子句是不是在GROUP BY

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'); 

任何帮帮我?

感谢

+0

我认为错误消息是extreemly自explanitory – RiggsFolly

+0

这是以前的,因国有_all字段组标准SQL应在select语句too_所以你可以重命名'SHIPPING_DATE ''在'年'来解决这个问题。 –

您的group by指定准确select柱:你的情况

->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') 
+0

@JasonJoslin注意,谢谢!我不确定MySQL,但是在一些dbms中,你也可以按位置排序。不知道 –

+0

仍然无法正常工作,位置和别名之间有什么区别,但我得到这样的错误:'未找到列:1054未知列'DATE_FORMAT(shipping_date,“group statement”中的'%M%Y''' (SQL:select count(*)as device,DATE_FORMAT(shipping_date,“%M%Y”)from'devices'where'shipping_date'is not null and'internal_use'= 0 and'devices'。'deleted_at'is null group by'DATE_FORMAT(shipping_date,“%M%Y”'order by'DATE_FORMAT(shipping_date,“%M%Y”'asc)'@StefanoZanini –

+0

我错过了一对括号,对不起。再次:) –

让我们试试这个。

它会工作...

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

您的代码按字母顺序排列,但每年都需要。看到它[链接](http://i.imgur.com/iJX00uI.jpg) –