我有一个提供错误结果的查询,我在这个查询中做错了什么
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/