Mysql select 查询计数和 Distinct 工作不正常

Mysql select query count & Distinct are not working properly

我正在使用 Laravel 8 开发电子商务网站。我编写了以下脚本来找出单个订单号下的总价和总数量。从以下脚本中得到错误,问题出在哪里请帮助我。
*起初我写行 mysql 然后我将转换 laravel 查询生成器。

SELECT COUNT (total_price) as totaPrice, COUNT (productqty) as proQnty
FROM (SELECT DISTINCT order_id FROM orderDetails)
LEFT JOIN ordertbl 
ON ordertbl.id = orderDetails.order_id;

In Your raw in missing the tablename alis for the subquery.. 您的原始查询应该是

SELECT COUNT(total_price) as totaPrice, COUNT(productqty) as proQnty
FROM (
    SELECT DISTINCT order_id FROM orderDetails
) T 
LEFT JOIN ordertbl ON ordertbl.id = T.order_id;

我猜你想对价格和数量求和,所以使用 SUM() 聚合函数。
您还应该将 ordertbl 加入 orderDetails 而不是相反:

SELECT ot.id,
       SUM(od.total_price) AS totaPrice, 
       SUM(od.productqty) AS proQnty
FROM ordertbl ot LEFT JOIN orderDetails od
ON ot.id = od.order_id
WHERE ot.id = ?
GROUP BY ot.id;

或者,没有连接:

SELECT SUM(total_price) AS totaPrice, 
       SUM(productqty) AS proQnty
FROM orderDetails 
WHERE order_id = ?;

? 替换为您想要的 id 顺序。