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

使用外部联接计数仅返回计数不为零的数据

  •  1
  • ytu  · 技术社区  · 7 年前

    假设我有两张桌子: user diary

    select count(id)
    from user
    where is_tester is false
    

    在这里,主键总是被称为 id . 上面这个查询给了我大约270000个用户,这意味着我有大约270000个用户。现在我想知道每个用户有多少日记。所以我去了:

    select u.id as user_id, u.dm_type, count(d.id) as bg_count
    from diary as d
    right join (
        select id, dm_type
        from user
        where is_tester is false
    ) as u
    on d.user_id = u.id
    where d.glucose_value > 0
    group by u.id, u.dm_type
    

    每个用户只能有一种 dm_type right join

    我提到过 Combining RIGHT JOIN with COUNT ,并根据接受答案的建议计算一个特定字段。


    用户

    | id | dm_type | is_tester |
    |----|---------|-----------|
    | 1  | 1       | False     |
    | 2  | 1       | False     |
    | 3  | 2       | False     |
    | 4  | no      | False     |
    | 5  | 2       | True      |
    

    日记

    | id | user_id | glucose_value |
    |----|---------|---------------|
    | 1  | 1       | -2            |
    | 2  | 1       | 80            |
    | 3  | 2       | 78            |
    | 4  | 2       | 100           |
    | 5  | 4       | 83            |
    | 6  | 5       | 90            |
    

    | user_id | dm_type | bg_count |
    |---------|---------|----------|
    | 1       | 1       | 1        |
    | 2       | 1       | 2        |
    | 3       | 2       | 0        |
    | 4       | no      | 1        |
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    您的查询的问题是 where

    当你处理这类问题时,我强烈建议 left join right join . 它的意思是“保留第一个表中的所有行,即使第二个表中没有匹配的行”。这通常比“在from子句的末尾保留任何表中的所有行,但我还没有看到”更容易理解。

    下一条规则是 桌子放在桌子上 哪里 on

    因此,您可以将查询表述为:

    select u.id as user_id, u.dm_type, count(d.id) as bg_count
    from user u left join
         diary d
         on d.user_id = u.id and d.glucose_value > 0
    where u.is_tester is false
    group by u.id, u.dm_type;
    

    不需要子查询。

        2
  •  1
  •   Fahmi    7 年前

    尝试左连接,它会给你所有的用户是否有日记计数 如果任何用户没有日记,那么它会给你空

    select u.id as user_id, u.dm_type, count(d.id) as bg_count from
    (select id, dm_type from user where is_tester is false)u
    left join diary d on d.user_id = u.id and d.glucose_value > 0
    group by u.id, u.dm_type