簡體   English   中英

MySQL查詢,剩下三個表與group by連接

[英]Mysql query, three tables left join with group by

我有提供錯誤結果的查詢,我在此查詢中做錯了什么嗎?

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 

您說“最大nViewCount應該為455,但它給出95124”。

但是在您的查詢中,您有SUM(bs.nViewCount) nViewCount,

那不是MAX(bs.nViewCount) nViewCount,嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM