代码之家  ›  专栏  ›  技术社区  ›  user3871

获取两个联接表的唯一记录计数

  •  0
  • user3871  · 技术社区  · 3 年前

    topics , sentences ,和 vocabulary . 句子和词汇都有各自的特点 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
    

    输出准确:

    enter image description here

    enter image description here

    但我想在句子和词汇上都表现出来。

    如果我用下面的方法来计算的话,它会同时计算句子和词汇的#词汇量(这是有意义的,因为它计算的是总行数),但不会分别计算句子和词汇的#总数。

    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
    

    enter image description here

    2 回复  |  直到 3 年前
        1
  •  1
  •   Bohemian    3 年前

    计算所有既有句子又有词汇的主题 ,要求两个子表中都存在行:

    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)
    
        2
  •  1
  •   Gordon Linoff    3 年前

    一个简单的方法是 count(distinct) :

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

    这是一种又快又脏的方法。在加入之前进行聚合可能会有更好的性能——或者相关的子查询。