Mysql 用户不是活动参与者的 COUNT 个

Mysql COUNT where user is NOT event participant

我想计算通过 table 参与的所有条目,以计算没有用户条目或显式用户没有条目条目的事件。

示例:我有 13 个事件和 2 个用户。

用户A(即我用于查询的用户)参加了两个活动(活动1和活动2)。 用户 B 还参加了两个事件(事件 2 和事件 3)。 没有人参加过任何其他活动。

如果我用 WHERE event.userId = "User A" 查询,我得到正确的计数 2

如果我查询 WHERE event.userId IS NULL 是否得到正确的计数 10

但是如果我查询 WHERE event.userId IS NULL OR event.userId != "User A" 我得到计数​​ 13(但它应该是 11)

SELECT 
    COUNT(DISTINCT event.id) AS count
FROM 
    event 
LEFT JOIN 
    event_participation participation ON participation.eventId=event.id

###    
# WITH USER    
###

# With this where clause I will get the correct count with the user
#WHERE participation.userId = "de9d0de5-5b2f-4108-8df7-6b89ec539679"            

###    
# WITHOUT USER
###

# Tried participation.userId != "de9d0de5-5b2f-4108-8df7-6b89ec539679" for ??? after OR, but this is not correct
#WHERE participation.userId IS NULL OR ???

解决方案应该是所有条目的单一计数结果,如下所示:

我怎样才能做到这一点?

计算连接的非匹配行以获得 'UserA'NOT 参与者的事件数:

SELECT COUNT(DISTINCT e.id) AS count
FROM event e LEFT JOIN  event_participation p 
ON p.eventId = e.id AND p.userId = 'UserA'
WHERE p.eventId IS NULL

或者因为 id 是 table event 的主键:

SELECT COUNT(*) AS count
FROM event e LEFT JOIN  event_participation p 
ON p.eventId = e.id AND p.userId = 'UserA'
WHERE p.eventId IS NULL

NOT EXISTS:

SELECT COUNT(*) AS count
FROM event e 
WHERE NOT EXISTS (
  SELECT 1 FROM event_participation p 
  WHERE p.eventId = e.id AND p.userId = 'UserA'
)

参见demo
结果:

> | count |
> | ----: |
> |    11 |