MySQL - 仅当组中的所有组都为NULL时才选择

时间:2017-04-19 16:42:49

标签: mysql

我的表格是这样的

ID|EID|priority|completed_forms|all_forms_in
1 |78 |NULL    |y              |y
2 |24 |NULL    |y              |y
3 |78 |1       |y              |y

我想要完成的任务: 如果它们共享相同的EID,则只选择行,并且所有行共享优先级为NULL,并且对于completed_forms和all_forms_in标记为“y”。

我尝试了什么:这是我当前的选择声明:

SELECT * FROM tasks 
WHERE priority IS NULL AND EID in 
(
SELECT * FROM 
    (select EID from tasks 
    WHERE completed_form = 'y' AND all_forms_in = 'y' ) as priority_check
GROUP BY EID having count(*) = 2
)

预期结果: 我希望这返回NO行,因为只有当两个行都为NULL时,select才能确保返回。在这种情况下,ID 1和ID 3都不共享NULL。相反,它返回ID 1。

1 个答案:

答案 0 :(得分:0)

您可以添加AND COUNT(priority) = 0COUNT,字段名称不计算空值),如下所示:

SELECT EID FROM tasks 
GROUP BY EID HAVING 
  COUNT(priority) = 0 AND
  COUNT(DISTINCT completed_form) = 1 AND MAX(completed_form) = 'y' AND
  COUNT(DISTINCT all_forms_in) = 1 AND MAX(all_forms_in) = 'y'AND
  COUNT(*) = 2