MySQL中满足特定条件时如何排除行

时间:2021-02-09 15:20:29

标签: mysql sql database

我有两个数据表。一张表包含参与者(Participants)的信息。以及一个包含活动的所有注册(注册商)的表格。

+----+-------+
| id | name  |
+----+-------+
| 1  | Peter |
+----+-------+
| 2  | John  |
+----+-------+

+-----------+----------+
| person_id | event_id |
+-----------+----------+
| 1         | 1        |
+-----------+----------+
| 2         | 2        |
+-----------+----------+
| 2         | 1        |
+-----------+----------+

我运行 MySQL 查询以获取事件注册商的信息。查询如下所示:

SELECT name
    FROM Participants
        INNER JOIN Registrars 
            ON Participants.id=Registrars.person_id
    WHERE 
        event_id = 1

现在我想构建一个查询,如果参与者也注册了事件 2,它将不会在查询结果中返回 reg。如何在一个查询中实现这一目标?

2 个答案:

答案 0 :(得分:1)

SELECT name
FROM Participants as p
    INNER JOIN Registrars as reg
        ON P.id=Reg.person_id
WHERE 
    reg.event_id = 1
 and not exists (select 1 from Registrars as strr where strr.event_id=2 and p.id=strr.person_id  )

答案 1 :(得分:1)

您可以按参与者分组并在 HAVING 子句中使用条件聚合来设置条件:

SELECT p.id, p.name
FROM Participants p INNER JOIN Registrars  r
ON p.id = r.person_id
WHERE r.event_id IN (1, 2)
GROUP BY p.id, p.name
HAVING MAX(r.event_id = 1) = 1 
   AND MAX(r.event_id = 2) = 0 

您可以通过以类似方式添加更多条件来扩展代码。