我有两张桌子
类别:
cat_id,cat_name
主题:
topic_id,cat_id,topic_name
我想获取所有cat_names的列表以及主题表中针对特定cat_id的主题数量,例如
Category Topics
----------------------
ABC 2
CDE 5
非常感谢快速帮助
由于
答案 0 :(得分:3)
使用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
答案 1 :(得分:2)
尝试此查询
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
答案 2 :(得分:0)
var countSelected = _.filter(Options, { 'Selected': true});
console.log(countSelected.length);
答案 3 :(得分:0)
试试这个
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
答案 4 :(得分:0)
尝试这个
SELECT Category.cat_name as Category,
(SELECT COUNT(topic_id) FROM Topics
WHERE Topics.cat_id = category.cat_id) AS Topics
FROM Category
答案 5 :(得分:0)
这是您在评论中显示的自己的查询:
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;