mysql中的count和join组合
我的表中有一个名为articles的表,其中包含列id、category\u id、article\u text 在类别表中:id、父类别和类别名称 我只想根据文章文本列出父类别名称和该类别中的文章总数。如果某个类别的父类别中有0,则表示其父类别。 我的问题是这样的mysql中的count和join组合,mysql,sql,Mysql,Sql,我的表中有一个名为articles的表,其中包含列id、category\u id、article\u text 在类别表中:id、父类别和类别名称 我只想根据文章文本列出父类别名称和该类别中的文章总数。如果某个类别的父类别中有0,则表示其父类别。 我的问题是这样的 select category_id from articles where article_text like '%somevalue%' select count(category_name) from category whe
select category_id from articles where article_text like '%somevalue%'
select count(category_name) from category where id=category_id
这个查询只是为了弄清楚想要什么。
请给出如何实现这一目标的想法。
感谢使用子查询,它将如下所示:
select count(category_name) from category where id= (select category_id from articles where article_text like '%somevalue%);
如果我理解正确的话,您正在寻找一个类别列表,其中包含每个类别中具有指定文本值的文章数。您可以通过子查询执行此操作:
select category_id,category_name,
(select count(*) from articles
where article_text like '%somevalue%'
AND articles.category_id = categories.category_id) as article_count
FROM Categories
使用左JOIN和groupby子句
SELECT category.id,
category.category_name,
COUNT(articles.id) AS articles_total
FROM category
LEFT JOIN articles ON category.id=articles.category_id
WHERE articles.article_text LIKE '%somevalue%'
GROUP BY category.id;