查找包含零个或一个相关记录的记录

时间:2017-05-31 05:36:46

标签: mysql

我有一个包含两个表的数据库:participantsresponses。参与者可以有零个,一个或多个响应。响应也可能不完整(在ended时间戳列中标记为NULL)。参与者可能有零或一个不完整的回复。

如何找到所有没有回复的参与者,或者只找到一个不完整的回复?

这是我首先尝试的SQL:

SELECT * FROM participants p
LEFT JOIN responses r
  ON p.id = r.id_participant
WHERE r.id IS NULL 
   OR (count(r.id) = 1 AND r.ended IS NULL)

我收到错误:Invalid use of group function

我尝试了一些变体(例如SELECT *, count(r.id) as numr等),但我没有在哪里。我相信我需要一种完全不同的方法。

2 个答案:

答案 0 :(得分:1)

我会使用条件计数来计算不完整答案的数量,并将其与答案总数进行比较。必须在having子句中对聚合函数进行过滤。

SELECT p.* 
FROM participants p
LEFT JOIN responses r 
  ON p.id = r.id_participant
GROUP BY p.id  --depending on mysql version you may have to list all fields from p here
HAVING count(*)=0 
  OR count(*)=1 
 AND count(IF(r.ended IS NULL, 1, NULL))=1

答案 1 :(得分:0)

不确定以下查询是否适合您,但请尝试:

SELECT p.*
FROM participants p
LEFT JOIN responses r ON p.id = r.id_participant
WHERE r.id IS NULL -- this will fetch participant with no response
OR EXISTS ( -- here will fetch participant with one incompleted response.
    SELECT 1
    FROM responses
    WHERE p.id = responses.id_participant
    GROUP BY responses.id_participant
    HAVING SUM(responses.ended IS NULL) = COUNT(1) AND COUNT(1) = 1
)