php - MySQL 语法错误 : ORDER BY clause is not in GROUP BY

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

有什么帮助吗?

谢谢

最佳答案

您必须在 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')

关于php - MySQL 语法错误 : ORDER BY clause is not in GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43658109/

相关文章:

Laravel 5.8 whereHasMorph "dot"语法不支持?

php - 我如何让 mysql 排名朝着正确的方向发展

php - 如何从 php 类中设置 Bootstrap 元素的样式?

mysql - 简单的选择查询返回空结果集?

php - 在 php 中执行 MySQL 时未选择数据库

php - Laravel 加入最新的 pressureMap 入口

javascript - React CRUD 应用程序中出现错误 : TypeError: Cannot destructure property 'id' of 'this.props.event' as it is undefined

php echo 如果查询为空

php - Yii框架如何更新所有记录?

php - 大量的小 SQL 语句会显着减慢我的网站速度吗