简体   繁体   English

编写带有计数的SQL查询

[英]Writing an SQL Query with a count

I have two tables 我有两张桌子

  1. Category: 类别:

    cat_id, cat_name cat_id,cat_name

  2. Topics: 主题:

    topic_id, cat_id, topic_name topic_id,cat_id,topic_name

I want to get list of all cat_names along with a count of topics in topics table against the particular cat_id like 我想获取所有cat_name的列表以及针对特定cat_id的主题表中的主题数量

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

Would really appreciate a fast help 非常感谢您的快速帮助

Thanks 谢谢

Use GROUP BY Clause 使用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

Try this query 试试这个查询

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;

Try this 尝试这个

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

TRY THIS 尝试这个

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

This is your own query that you are showing in your comments: 这是您要在评论中显示的您自己的查询:

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;

First of all there is a syntax error. 首先,存在语法错误。 Instead of 代替

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

this would have to be 这将是

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

Then you are reading the topics table twice, once in the join, once in the subquery. 然后,您将读取主题表两次,一次在联接中,一次在子查询中。 So this looks like two tries mixed in one statement. 因此,这看起来像是两次尝试混合在一个语句中。 Here are the two options separated: 这是两个分开的选项:

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;

Or: 要么:

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