所以我有这个问题:
SELECT Posts.[Post ID], Count(Comments.[Comment ID]) AS [CountOfComment ID],
Count(Shares.[Share ID]) AS [CountOfShare ID],
Count(Likes.[Like ID]) AS [CountOfLike ID]
FROM ((Posts INNER JOIN Likes ON Posts.[Post ID] = Likes.[Post ID])
INNER JOIN Shares ON Posts.[Post ID] = Shares.[Post ID])
INNER JOIN Comments ON Posts.[Post ID] = Comments.[Post ID]
WHERE posts.[post id] = 5
GROUP BY Posts.[Post ID];
哪个应该返回结果:
post.[post id]= 5
CountofcommentID= 4
CountofShareID = 5
CountofLikeID = 15
但我获得post.[post id] = 5, and the rest =300.
我知道这是因为它正在计算所有ID的所有排列,但我如何更改它以获得我想要的结果?
答案 0 :(得分:0)
加入时,每个组合都会有一行。因此,count会计算每一行,其值与null不同。所以,你想要的是计算DISTINCT ID。即:
SELECT Posts.[Post ID], Count(DISTINCT Comments.[Comment ID]) AS [CountOfComment ID],
Count(DISTINCT Shares.[Share ID]) AS [CountOfShare ID],
Count(DISTINCT Likes.[Like ID]) AS [CountOfLike ID]
FROM ((Posts INNER JOIN Likes ON Posts.[Post ID] = Likes.[Post ID])
INNER JOIN Shares ON Posts.[Post ID] = Shares.[Post ID])
INNER JOIN Comments ON Posts.[Post ID] = Comments.[Post ID]
WHERE posts.[post id] = 5
GROUP BY Posts.[Post ID];
如果系统不支持此语法,则可能需要执行子查询:
Select Posts.[Post ID],
(Select count([Share ID]) from Shares where Posts.[Post ID] = Shares.[Post ID]) as SharesCount
FROM Posts
WHERE posts.[post id] = 5;
答案 1 :(得分:0)
你误解了COUNT()
的作用。它计算非NULL
值的数量。正确的解决方案是使用COUNT(DISTINCT)
。由于MS-Access不支持COUNT(DISTINCT)
,您可能会将其解释为"获取功能数据库"。
在MS Access中,您可以使用某种类型的子查询来执行此操作。这是一种方法:
SELECT p.[Post ID],
(SELECT COUNT(*)
FROM (SELECT DISTINCT [Post Id], [Comment ID]
FROM Comments as c
) as c
WHERE c.[Post Id] = p.[Post Id]
) as [CountOfComment ID],
(SELECT COUNT(*)
FROM (SELECT DISTINCT [Post Id], [Share ID]
FROM Shares as s
) as s
WHERE s.[Post Id] = p.[Post Id]
) as [CountOfShare ID],
(SELECT COUNT(*)
FROM (SELECT DISTINCT [Post Id], [Like ID]
FROM Likes as l
) as l
WHERE l.[Post Id] = p.[Post Id]
) as [CountOfLikes ID]
FROM Posts as p
WHERE p.[post id] = 5
GROUP BY p.[Post ID];