以下查询为我返回奇怪的结果:
SELECT
`Statistics`.`StatisticID`,
COUNT(`Votes`.`StatisticID`) AS `Score`,
COUNT(`Views`.`StatisticID`) AS `Views`,
COUNT(`Comments`.`StatisticID`) AS `Comments`
FROM `Statistics`
LEFT JOIN `Votes` ON `Votes`.`StatisticID` = `Statistics`.`StatisticID`
LEFT JOIN `Views` ON `Views`.`StatisticID` = `Statistics`.`StatisticID`
LEFT JOIN `Comments` ON `Comments`.`StatisticID` = `Statistics`.`StatisticID`
GROUP BY `Statistics`.`StatisticID`
LIMIT 0, 10
我在如下表格结构中查询:
(仅与Statistics.StatisticID = 8
相关的数据)
StatisticID
8
StatisticID
8
8
StatisticID
8
8
8
8
8
现在,如果我运行此查询,我会得到以下结果集:
StatisticID Score Views Comments
8 5 5 5
我知道5来自哪里 - 评论的数量 - 如果我把评论声明拿出来,这就行了。任何人都可以调试这个,因为这是我无法实现的(我对SQL相对较新)。
谢谢, 罗斯
答案 0 :(得分:4)
当像这样加入时,你会在你在其他表中找到mathing行时多次复制数据。如果每个表中只有1个对应的行,这很好。
在没有分组的情况下运行此查询,您将了解为什么在所有计数上获得相同的结果。然而,我会猜到你将得到10作为每个领域的计数(1 * 2 * 5) 如果你想解决这个问题,你需要为每个计数调用一个子选择。
SELECT s.`StatisticID`, (SELECT COUNT(*) FROM Votes WHERE Votes.StatisticID = s.StatisticID) AS Score, (SELECT COUNT(*) FROM Views WHERE Views.StatisticID = s.StatisticID) AS Views, (SELECT COUNT(*) FROM Comments WHERE Comments.StatisticID = s.StatisticID) AS Comments, FROM `Statistics` s LIMIT 0, 10
如果外部结果很大,则存在某些性能问题。您可以通过加入其中一个表来优化它,但是我不确定queryparser是否足够聪明,每个分组项目只能运行1次。希望它会。否则,您可以将其拆分为不同的查询。
答案 1 :(得分:2)
假设您在投票/观看/评论中有一个id字段或类似字段:
SELECT
`Statistics`.`StatisticID`,
COUNT(DISTINCT `Votes`.`VoteID`) AS `Score`,
COUNT(DISTINCT `Views`.`ViewID`) AS `Views`,
COUNT(DISTINCT `Comments`.`CommentID`) AS `Comments`
FROM `Statistics`
LEFT JOIN `Votes` ON `Votes`.`StatisticID` = `Statistics`.`StatisticID`
LEFT JOIN `Views` ON `Views`.`StatisticID` = `Statistics`.`StatisticID`
LEFT JOIN `Comments` ON `Comments`.`StatisticID` = `Statistics`.`StatisticID`
GROUP BY `Statistics`.`StatisticID`
LIMIT 0, 10
没有测试过,但认为它应该有效。 (我们必须使用不同的字段,因为统计ID在给定的组中总是相同的......)