mysql查询,左三张表用group by连接

标签 mysql sql-order-by left-join

我有一个提供错误结果的查询,我在这个查询中做错了什么

SELECT   b.nBoutiqueID                       ,
         b.sBoutiqueName                     ,
         b.Status                            ,
         SUM(bs.nViewCount)      nViewCount       ,
         SUM(ps.nViewCount)      nProductViewCount,
         SUM(ps.nLinkClickCount) nLinkClickCount  ,
         SUM(ps.nWishListCount)  nWishListCount   ,
         SUM(ps.nReferredCount)  nReferredCount
FROM     boutique b
         LEFT JOIN boutique_stats bs
         ON       b.nBoutiqueID=bs.nBoutiqueID
         LEFT JOIN product_stats ps
         ON       ps.nBoutiqueID=b.nBoutiqueID
WHERE    b.bDeleted             =0
GROUP BY b.nBoutiqueID
ORDER BY ps.nProductID DESC

查询没有给出任何错误,但产生了错误的结果。我正在使用 Mysql。

对于 nBoutiqueID=1 的特定实例,nViewCount 的最大总和应为 455,但它给出了 95124。这是巨大的差异。有人知道为什么吗?

最佳答案

看来您得到的是查询的某种笛卡尔积...尝试从子查询中获取 SUM() 值...

SELECT
      b.nBoutiqueID, 
      b.sBoutiqueName, 
      b.Status, 
      bs.StatsViewCount,
      ps.ProductViewCount, 
      ps.ProductLinkClickCount, 
      ps.ProductWishListCount, 
      ps.ProductReferredCount 
   FROM     
      boutique b 
         LEFT JOIN ( select nBoutiqueID, sum( nViewCount ) as StatsViewCount
                        from boutique_stats 
                        group by nBoutiqueID ) bs 
            ON b.nBoutiqueID = bs.nBoutiqueID 
         LEFT JOIN ( select SUM(nViewCount) ProductViewCount, 
                             SUM(nLinkClickCount) ProductLinkClickCount, 
                             SUM(nWishListCount) ProductWishListCount, 
                             SUM(nReferredCount)  ProductReferredCount 
                        from product_stats 
                        group by nBoutiqueID ) ps 
            ON ps.nBoutiqueID=b.nBoutiqueID 
   WHERE    
      b.bDeleted = 0 
   ORDER BY 
      ps.nProductID DESC 

关于mysql查询,左三张表用group by连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3802499/

相关文章:

mysql - 在没有表单的情况下在 Rails 中发出 AJAX 请求

mysql - 使用自定义配置文件字段的 SQL Moodle

php - SQL PHP 插入表

mysql - mysql 将两行合并为一行

c# - Linq order by 没有订购任何东西

mysql - 加速使用全文连接的 SQL 查询

PHP MYSQL 使用 order by 子句从表中查找行号/排名

c# - 将 OrderBy 与 Entity Framework 和 ObjectContext.CreateQuery(T) 结合使用时出现问题

mysql - 删除mysql和group中Join语句中的重复项

MySql 查询连接