我需要获取新闻的数量,它给了我错误
专栏' News.NewsId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
select News.NewsId
, News.NewsTitle
, COUNT(News.NewsId) as Total
from News inner join NewsCategory on News.NewsId = NewsCategory.NewsId
where NewsCategory.CategoryId in (Select CategoryId
from Category
where CategoryName = 'travel'
or CategoryName = 'Technology'
or CategoryName = 'Sport')
答案 0 :(得分:0)
您需要按列NewsId
和NewsTitle
select News.NewsId
, News.NewsTitle
, COUNT(News.NewsId) as Total
from News inner join NewsCategory on News.NewsId = NewsCategory.NewsId
where NewsCategory.CategoryId in
(Select CategoryId
from Category
where CategoryName IN ('travel','Technology','Sport'))
GROUP BY News.NewsId
, News.NewsTitle
或者您可以将查询编写为
select News.NewsId
, News.NewsTitle
, COUNT(News.NewsId) as Total
from News
inner join NewsCategory on News.NewsId = NewsCategory.NewsId
inner join Category on Category.CategoryId = NewsCategory.CategoryId
where Category.CategoryName IN ('travel','Technology','Sport'))
GROUP BY News.NewsId, News.NewsTitle
答案 1 :(得分:0)
像这样使用ti:
select News.NewsId, News.NewsTitle, COUNT(News.NewsId) as Total from News group by News.NewsId, News.NewsTitle
inner join
NewsCategory
on News.NewsId = NewsCategory.NewsId where NewsCategory.CategoryId in (Select CategoryId from Category where CategoryName = 'travel' or CategoryName = 'Technology' or CategoryName = 'Sport')'Technology' or CategoryName = 'Sport')
您正在使用计数,这就是您需要按字段分组的原因,包括在您的计数中(News.NewsId)
根据每个NewsId显示每个类别的计数:
select count(1), a.NewsId, a.NewsTitle,b.category from
(select NewsId, NewsTitle from tbl_news)as a
left JOIN
(select NewsId, categoryid,Category from tbl_category) as b
on a.newsid = b.newsid GROUP BY a.NewsTitle,b.category
答案 2 :(得分:0)
只需使用两个连接和一个group by
:
select n.NewsId, n.NewsTitle, COUNT(*) as Total
from News n inner join
NewsCategory nc
on n.NewsId = nc.NewsId join
Category c
on nc.CategoryId = c.CategoryId
where c.CategoryName in ('travel', 'Technology', 'Sport')
group by n.NewsId, n.NewsTitle;