2017-04-27 149 views
1

我有一個查詢,我想通過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 ''在'年'來解決這個問題。 –

回答

1

您的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

我錯過了一對括號,對不起。再次:) –

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) –