繁体   English   中英

编写带有计数的SQL查询

[英]Writing an SQL Query with a count

我有两张桌子

  1. 类别:

    cat_id,cat_name

  2. 主题:

    topic_id,cat_id,topic_name

我想获取所有cat_name的列表以及针对特定cat_id的主题表中的主题数量

Category       Topics
----------------------
ABC            2
CDE            5

非常感谢您的快速帮助

谢谢

使用GROUP BY子句

SELECT COUNT(*) AS 'Topics', cat_id AS 'Category' FROM Category JOIN Topics ON Category.cat_id = Topics.cat_id
GROUP BY cat_id

试试这个查询

select a.cat_name as category, count(*) as Topics
from category a
  join Topics b on a.cat_id=b.cat_id
group by a.cat_name
select cat_name as category,count(topic_id) as topics
from Category
  join Topics on Category.cat_id=Topics.cat_id
group by Category.cat_name;

尝试这个

select cat_name, count(*) as counting
from Category as cat 
  inner join Topics as t on cat.cat_id=t.cat_id
group by cat_name

尝试这个

SELECT Category.cat_name as Category,
       (SELECT COUNT(topic_id) FROM  Topics
        WHERE Topics.cat_id = category.cat_id) AS Topics 
FROM Category

这是您要在评论中显示的您自己的查询:

select 
  category.cat_id as id, 
  category.cat_name as category, 
  count(select * from topics where topics.topic_id=id) as topics
from category 
inner join topics on category.cat_id=topics.cat_id;

首先,存在语法错误。 代替

count(select * from topics where topics.topic_id=id) as topics

这将是

(select count(*) from topics where topics.topic_id=id) as topics

然后,您将读取主题表两次,一次在联接中,一次在子查询中。 因此,这看起来像是两次尝试混合在一个语句中。 这是两个分开的选项:

select 
  category.cat_id as id, 
  category.cat_name as category, 
  (select count(*) from topics where topics.topic_id = category.id) as topics
from category;

要么:

select 
  category.cat_id as id, 
  category.cat_name as category, 
  count(topics.topic_id) as topics
from category 
left join topics on category.cat_id = topics.cat_id
group by category.cat_id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM