我想要计算许多喜欢我在我的数据库中的特定帖子我创建了这个简单的查询显示有多少像我有一个资源“帖子”但是当我添加到主脚本时它会错过它
SELECT COUNT(Likes.resourceID) AS Count_resID, Resources.Id
FROM Likes INNER JOIN
Resources ON Likes.resourceID = Resources.Id
GROUP BY Resources.Id
Result
Count_resID Id
----------- -----------
1 53
2 54
2 60
2 61
1 62
(5 row(s) affected)
SELECT a.Id, a.summary, a.pageId, a.name, a.createdOn, COUNT(Likes.resourceID) AS Count_resID
FROM Resources AS a INNER JOIN
Topics_Resources AS b ON a.Id = b.ResourceID INNER JOIN
Skills_Resources AS c ON a.Id = c.ResourceID INNER JOIN
Types AS d ON a.typeId = d.Id INNER JOIN
Modules AS m ON a.ModuleId = m.ModuleID INNER JOIN
ContentItems AS ci ON m.ModuleID = ci.ModuleID INNER JOIN
Tabs AS t ON t.TabID = ci.TabID INNER JOIN
TabModules AS tb ON t.TabID = tb.TabID INNER JOIN
Likes ON a.Id = Likes.resourceID LEFT OUTER JOIN
HtmlText AS h ON tb.ModuleID = h.ModuleID
GROUP BY a.Id, a.summary, a.pageId, a.name, a.createdOn
Id summary pageId name createdOn Count_resID
----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
53 jihuih http://localhost/ideapark/testpage99.aspx jklhjk 2013-05-10 07:24:21.833 12
54 1 http://localhost/ideapark/testpage33.aspx sdvs 2013-05-09 07:24:21.833 2
60 sdvsdv http://localhost/ideapark/tesCreatedate.aspx dsvsdv 2013-05-13 07:32:13.133 8
61 newtest http://localhost/ideapark/newtest.aspx newTest 2013-05-13 10:35:08.027 2
62 sdvsdvds http://localhost/ideapark/page21.aspx svdsvs 2013-05-14 14:06:15.603 35
(5 row(s) affected)
答案 0 :(得分:1)
根据您的结果更改,您使用加入表格的标准之一存在问题。您必须确保连接中的表与基表具有一对一的比率。
答案 1 :(得分:1)
问题是您正在连接多个表,并且这些表中的多个表具有1-n关系。您正在获得笛卡尔产品,而您并不期望它。
解决此问题的正确方法是在加入之前进行子查询汇总。
但是,您可以使用count(distinct)
进行快速简便的修复。请改用此select
语句:
SELECT a.Id, a.summary, a.pageId, a.name, a.createdOn,
COUNT(distinct Likes.Id) AS Count_resID;
这假设likes
中的每条记录都有id
来唯一标识它。
更好的解决方法(特别是如果重新使用此查询)涉及更改from
联接:
TabModules AS tb ON t.TabID = tb.TabID INNER JOIN
Likes ON a.Id = Likes.resourceID LEFT OUTER JOIN
类似于:
. . .
TabModules AS tb ON t.TabID = tb.TabID INNER JOIN
(select l.resourceId, count(*) as NumLikes
from Likes l
) l ON a.Id = l.resourceID LEFT OUTER JOIN
. . .
然后在NumLikes
子句中引用select
。