统计x条件下有多少行与table没有关系

Count how many rows have no relationship with a table under x conditions

我有一个userstable和一个hobbiestable

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 查询来统计有多少用户 没有 有 'drawing' 或 'singing' 的爱好。在这个例子中,只有 Karen 会被计算在内,因为他们是唯一一个不喜欢唱歌或画画的人。

您可以使用 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') ;
  

您可以使用 not exists 运算符:

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

容易

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'))