Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql中的count和join组合_Mysql_Sql - Fatal编程技术网

mysql中的count和join组合

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

我的表中有一个名为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 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;