我有 3 个表:Product
, Shares
,Likes
由ProductID
. 我想要做的是在一个查询中选择所有产品和这些产品COUNT(shares)
。COUNT(likes)
首先,是否可以只使用一个查询?如果可能的话我该怎么做?最重要的是,当用户将鼠标悬停在进行 Ajax 调用并获得喜欢和共享数据时,我应该选择所有产品并显示吗?提前致谢。
干得好:
SELECT
p.id AS 'product id',
IFNULL(COUNT(DISTINCT s.id), 0) AS 'total shares',
IFNULL(COUNT(DISTINCT l.id), 0) AS 'total likes'
FROM
products p
LEFT JOIN shares s ON s.product_id = p.id
LEFT JOIN likes l ON l.product_id = p.id
GROUP BY p.id
IFNULL
将处理没有分享或点赞的情况;DISTINCT
应该在那里,否则当加入喜欢时,一份分享将被多次计算(反之亦然)。
它可以在一个查询中完成。在我的头顶上像
SELECT
product_id,
COUNT(likes.product_id) as likes,
COUNT(SELECT share_id FROM shares WHERE product_id = p.product_id) as shares
FROM product p
LEFT JOIN likes USING(product_id)
还是看表演吧。确保你有你的索引等
SELECT
p.ProductID,
COUNT(s.ProductID) AS SharesCount,
COUNT(l.ProductID) AS LikesCount
FROM
Products p LEFT JOIN Shares s
ON P.ProductID = s.ProductID
LEFT JOIN likes l
ON P.ProductID = l.ProductID
GROUP BY p.ProductID