首页 > 解决方案 > 获取两个连接表的唯一记录数

问题描述

我有三个表:topicssentencesvocabulary。句子和词汇都有一个belongsTo topic_id,但并非所有主题都必须同时有词汇和句子。我想计算所有既有句子又有词汇的主题。

如果我一次做一张桌子,我就可以了:

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

输出是准确的:

在此处输入图像描述

句子也一样:

在此处输入图像描述

但我想对句子和词汇都进行高效处理。

如果我按照以下方式进行操作,它会计算句子和词汇的词汇量(这是有道理的,因为它计算总行数),但不会分别计算 total_sentences 和 total_vocabulary 的唯一计数。

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

在此处输入图像描述

标签: sqlpostgresql

解决方案


一种简单的方法是count(distinct)

    t.id as topic_id,
    count(distinct s.id) as total_sentences,
    count(distinct v.id) as total_vocabulary

这是快速而肮脏的方法。在加入之前进行聚合可能具有更好的性能 - 或相关的子查询。


推荐阅读