Sql 获取两个联接表的唯一记录计数
我有三张表格:主题、句子和词汇。句子和词汇都有一个belongstototototopic\u id,但并非所有的主题都有词汇和句子。我想统计一下所有既有句子又有词汇的主题 如果我一次只做一张桌子,它就可以工作了:Sql 获取两个联接表的唯一记录计数,sql,postgresql,Sql,Postgresql,我有三张表格:主题、句子和词汇。句子和词汇都有一个belongstototototopic\u id,但并非所有的主题都有词汇和句子。我想统计一下所有既有句子又有词汇的主题 如果我一次只做一张桌子,它就可以工作了: select * from ( select t.id as topic_id, count(v.id) total_vocabulary from topics t left join vocabulary v on
select
*
from (
select
t.id as topic_id,
count(v.id) total_vocabulary
from topics t
left join vocabulary v on (v.topic_id = t.id)
where v.locale_id = 1
group by t.id
order by t.id
) as topics_with_vocabulary
where total_vocabulary > 0
输出准确:
同样适用于以下句子:
但我想在句子和词汇上都表现出色
如果我按照下面的方法来做的话,它是计算句子和词汇的词汇量,这是有意义的,因为它是计算行总数,但不是单独计算句子总数和词汇总数
select
*
from (
select
t.id as topic_id,
count(s.id) as total_sentences,
count(v.id) as total_vocabulary
from topics t
left join sentences s on (s.topic_id = t.id)
left join vocabulary v on (v.topic_id = t.id)
where s.locale_id = 1
and v.locale_id = 1
group by t.id
order by t.id
) as topics_with_sentences
where total_sentences > 0
or total_vocabulary > 0
一个简单的方法是:
这是一种既快又脏的方法。加入前聚合可能具有更好的性能或相关子查询。若要计算同时包含句子和词汇表的所有主题,要求两个子表中都存在行:
select count(*)
from topics t
where exists (select * from vocabulary where topic_id = t.id)
and exists (select * from sentences where topic_id = t.id)
select count(*)
from topics t
where exists (select * from vocabulary where topic_id = t.id)
and exists (select * from sentences where topic_id = t.id)