如何通过左JOIN,COUNT和GROUP在Laravel中编写此SQL查询?
该数据库具有“订单”和“客户”表。 我无法将它们连接到这个USGBU请求。
SELECT orders.serial_number,
count(orders.order_id) as count ,
customers.customer_name FROM orders
LEFT JOIN customers ON
orders.customer_id = customers.customer_id
GROUP By orders.serial_number;
我编写的代码如下:
$orders = Orders::select("orders.serial_number","customers.customer_name", DB::raw("COUNT(orders.order_id) as count"))
->leftJoin('customers','orders.customer_id','=','customers.customer_id')
->groupBy('orders.serial_number')
->get();
错误消息显示如下:
SQLSTATE[42000]: Syntax error or access violation: 1055 'alqorshop.customers.customer_name' isn't in GROUP BY (SQL: select `orders`.`serial_number`, `customers`.`customer_name`, COUNT(orders.order_id) as count from `orders` left join `customers` on `orders`.`customer_id` = `customers`.`customer_id` group by `orders`.`serial_number`)
The database has "orders" and "customers" tables.
I can't connect them to this usgbu request.
SELECT orders.serial_number,
count(orders.order_id) as count ,
customers.customer_name FROM orders
LEFT JOIN customers ON
orders.customer_id = customers.customer_id
GROUP By orders.serial_number;
The code I wrote is as follows:
$orders = Orders::select("orders.serial_number","customers.customer_name", DB::raw("COUNT(orders.order_id) as count"))
->leftJoin('customers','orders.customer_id','=','customers.customer_id')
->groupBy('orders.serial_number')
->get();
An error message appears as follows:
SQLSTATE[42000]: Syntax error or access violation: 1055 'alqorshop.customers.customer_name' isn't in GROUP BY (SQL: select `orders`.`serial_number`, `customers`.`customer_name`, COUNT(orders.order_id) as count from `orders` left join `customers` on `orders`.`customer_id` = `customers`.`customer_id` group by `orders`.`serial_number`)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此SQL的正确查询是:
或者
您没有在您的组中按子句中包含“ customer.customer_name”,这就是为什么会出现错误的原因。
要么通过查询添加客户。
The correct query for this sql is:
OR
You did not include "customers.customer_name" in your group by clause which is why it's giving an error.
Either add customers.customer_name to your group by query or remove customers.customer_name from select statement
您的查询不正确 - 您需要将
usterces.customer_name
添加到条款的组或从
select> SELECT
条款中删除。Your query is not correct -- you need to add
customers.customer_name
to theGROUP BY
clause or remove it from theSELECT
clause