简体   繁体   English

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

[英]Mysql select query count & Distinct are not working properly

I am developing an eCommerce website using Laravel 8. I write the following script for find out total price & total quantity under a single order number.我正在使用 Laravel 8 开发一个电子商务网站。我编写以下脚本来找出单个订单号下的总价格和总数量。 From following script getting the ERROR where is the problem please help me.从以下脚本获取错误,问题出在哪里,请帮助我。
*At first I write row mysql then i will convert laravel query Builder. *首先我写行 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.. Your raw query should be在您的原始中缺少子查询的表名 alis ..您的原始查询应该是

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;

I guess you want to sum the prices and quantities, so use SUM() aggregate function.我猜你想对价格和数量求和,所以使用SUM()聚合 function。
Also you should do a LEFT join of ordertbl to orderDetails and not the other way around:此外,您应该将orderDetails LEFT连接到ordertbl ,而不是相反:

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;

Or, without a join:或者,没有连接:

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

Replace ?更换? with the id of the order that you want.带有您想要的订单的id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM