有两张桌子。第1名: blogCategories ,第2名:博客。 表 blogCategories 只有2个字段,id和categoyName。之前插入了许多类别名称。表博客包含id,blogCatID,标题,博客,日期文件。 表博客中有许多记录。但并非所有categoryName都被使用。 我尝试获取一个categoryNames列表及其在博客中的使用次数。如果在博客中没有使用categoryName,我需要0(零)。
我使用了下面的查询。但是,即使没有使用,categoryNames也会获得1号计数。
SELECT DISTINCT categoryName, COUNT(*) AS totalBlogCount
FROM
(SELECT bc.categoryName
FROM
blogCategories bc
LEFT JOIN blog b ON bc.id=b.blogCatID) AS tot
GROUP BY categoryName
答案 0 :(得分:2)
Select bc.CategoryName, NullIf(bCounts.NumberOfTimesUsed,0) As NumberOfTimesUsedInBlog
From BlogCategories bc
Left Join
(Select blogCatID, Count(*) as NumberOfTimesUsed
From Blog Group By BlogCatID) bCounts
On bCounts.BlogCatID = bc.ID
答案 1 :(得分:2)
以下查询将为您提供categoryName和使用次数。如果没有使用,则会将0
作为count(null value)=0
SELECT bc.categoryName, COUNT(b.blogCatID) AS totalBlogCount
FROM blogCategories bc Left JOIN blog b ON bc.id=b.blogCatID
GROUP BY categoryName
输出看起来像
inspirational 5
technical 2
political 0
random 3
答案 2 :(得分:1)
SELECT bc.categoryName, COUNT(*) AS totalBlogCount
FROM blogCategories bc INNER JOIN blog b ON bc.id=b.blogCatID
GROUP BY categoryName
答案 3 :(得分:1)
首先计算使用过的blogCatID:
select blogCatID, count(*) as Number
from blog
group by blogCatID
稍后您可以找到未使用的blogCategories:
select *
from blogCategories as bc
where bc.id not in (select blogCatID
from blog
group by blogCatID)
接下来尝试一下blogCategories列表以及博客中的使用次数(如果不使用则为0):
select isnull(b.numb, 0) as num, bc.*
from blogCategories as bc left join (select blogCatID, count(*) as numb
from blog
group by blogCatID) as b ON bc.id b.blogCatID