【问题标题】:Count how many rows have no relationship with a table under x conditions计算x条件下有多少行与一个表没有关系
【发布时间】:2021-11-10 22:43:34
【问题描述】:

我有一个users 表和一个hobbies

users

id | name   |
---+--------+
1  | John   |
2  | Jim    |
3  | Karen  |
hobbies

id | user_id | hobby   |
---+---------+---------+
1  | 1       | drawing |
2  | 1       | singing |
3  | 2       | coding  |
4  | 2       | drawing |
6  | 3       | chess   |
7  | 3       | coding  |

我需要一个 SQL 查询来计算有多少用户不要有“绘画”或“唱歌”作为爱好。在这个例子中,只有 Karen 会被计算在内,因为他们是唯一不喜欢唱歌或画画的人。

【问题讨论】:

    标签: mysql sql database select


    【解决方案1】:

    您可以使用not exists 运算符:

    SELECT *
    FROM   users u
    WHERE  NOT EXISTS (SELECT *
                       FROM   hobbies h
                       WHERE  hobby IN ('drawing', 'singing') AND
                              h.user_id = u.id)
    

    【讨论】:

    • SELECT * with EXISTS 非常有意义,或者与其他任何东西一样有意义。在存在子句中,没有“选择” - 您可以使用 select 1/0 来证明这一点...您不会产生除以零错误。
    • 这正是我想要的。由于仅使用一个 NOT EXISTS 运算符,它也比其他类似答案快 100 毫秒。
    【解决方案2】:

    您可以使用 not exists 。 . .两次:

    select u.*
    from users u
    where not exists (select 1 from hobbies h where h.user_id = u.id and h.hobby = 'singing') and
          not exists (select 1 from hobbies h where h.user_id = u.id and h.hobby = 'dancing') ;
      
    

    【讨论】:

      【解决方案3】:

      简单

      declare @users table(id int, name varchar(15))
      declare @hobbies table(id int, user_id int, hobby varchar(15))
      
      insert into @users
      values
       (1,'John'),
       (2,'Jim'),
       (3,'Karen')
      
      insert into @hobbies
      values
       (1,1,'drawing'),
       (2,1,'singing'),
       (3,2,'coding'),
       (4,2,'drawing'), 
       (6,3,'chess'),
       (7,3,'coding')
      
      
      select count(*)
      from @users u
      left join
      (select u.id
      from @users u
          inner join @hobbies h
          on h.user_id = u.id
      where h.hobby in ('drawing','singing'))users_with_hobbies  on users_with_hobbies.id = u.id
      where users_with_hobbies.id is null
      
      -- or
      
      select count(*)
      from @users u   
      where not id in (select u.id
         from @users u
          inner join @hobbies h
          on h.user_id = u.id
      where h.hobby in ('drawing','singing'))
      
      -- or   
      select count(*)
      from @users u   
      where not exists (select null
        from @hobbies h   
        where h.user_id = u.id and h.hobby in ('drawing','singing'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        相关资源
        最近更新 更多