如何在 JOIN MySQL 中进行 GROUP BY 和 COUNT(*)

Posted

技术标签:

【中文标题】如何在 JOIN MySQL 中进行 GROUP BY 和 COUNT(*)【英文标题】:How to do GROUP BY and COUNT(*) in JOIN MySQL 【发布时间】:2021-03-25 11:58:08 【问题描述】:

我有名为 company、product、purchase_order、skid、process_record 的表,我想要 mysql 查询结果如下。

我试过了

SELECT s.id as skidId, s.skidBarcode, po.poNumber, s.companyId, c.companyName, p.productId , p.productName, totalProcessed 
FROM skid s 
INNER JOIN company c ON s.companyId = c.id 
INNER JOIN purchase_order po on s.purchaseOrderId = po.id 
INNER JOIN product prdct on p.productId = prdct.id 
LEFT JOIN (SELECT skidID, productId , COUNT(*) as processedQuantity FROM process_record GROUP BY productId ) p ON p.skidID= s.id 
WHERE s.status = 'closed' ORDER By s.companyId,s.id

但是,此查询结果在某些行上将处理的数量计数为 NULL 和随机错误计数。

如何获得所需的 MySQL 查询输出,如屏幕截图所示?

【问题讨论】:

见meta.***.com/questions/333952/… 【参考方案1】:

我添加了GROUP BY skidID, productId 而不是GROUP BY productId,它解决了这个问题。

 SELECT s.id as skidId, s.skidBarcode, po.poNumber, s.companyId, c.companyName, p.productId , p.productName, totalProcessed 
    FROM skid s 
LEFT JOIN (SELECT skidID, productId , COUNT(*) as processedQuantity FROM process_record GROUP BY skidID, productId ) p ON p.skidID= s.id 
    INNER JOIN company c ON s.companyId = c.id 
    INNER JOIN purchase_order po on s.purchaseOrderId = po.id 
    INNER JOIN product prdct on p.productId = prdct.id 
    
    WHERE s.status = 'closed' ORDER By s.companyId,s.id

【讨论】:

选择 s.id 作为skidId,s.barCode,po.orderNumber,s.skidContent,s.companyId,s.close_status,c.companyName,IFNULL(p.productId,0) 作为productId, IFNULL(p.processedQuantity,0) as processesQuantity FROM skid s LEFT JOIN (SELECT skidID, productId, COUNT(*) as processesQuantity FROM process_record GROUP BY skidID, productId ) p ON p.skidID= s.id INNER JOIN company c ON s .companyId = c.id INNER JOIN purchase_order po on s.purchaseOrderId = po.id WHERE s.close_status != 'ClosedAndInvoiced' ORDER By s.companyId,s.id

以上是关于如何在 JOIN MySQL 中进行 GROUP BY 和 COUNT(*)的主要内容,如果未能解决你的问题,请参考以下文章

Mysql Group Join 优化问题

如何在 Teradata SQL 中使用 LEFT JOIN 对查询中的非聚合参数进行 GROUP BY?

在 JOIN 查询中使用 Mysql GROUP_CONCAT

MySQL Join Group By 和 Group Concat

如何在mysql中group by week

带有 LEFT JOIN 和 GROUP BY 的 COUNT(*) 在 MySQL 中包含 NULL