Mysql 查询,仅当其所有记录在特定列中都为null时才返回true

Mysql 查询,仅当其所有记录在特定列中都为null时才返回true,mysql,sql,count,having-clause,sql-null,Mysql,Sql,Count,Having Clause,Sql Null,假设有一个表赋值,其列为 分配id 转让人 任务id 受让人 同一任务id可由指派人指派给1个以上的指派人。 目前,我有一个任务分配给2个工作人员。让我们看看下表中的示例: +---------------+----------+---------+----------+ | assignment_id | assignor | task_id | assignee | +---------------+--------------------+----------+ | 1

假设有一个表赋值,其列为

  • 分配id
  • 转让人
  • 任务id
  • 受让人
同一任务id可由指派人指派给1个以上的指派人。 目前,我有一个任务分配给2个工作人员。让我们看看下表中的示例:

+---------------+----------+---------+----------+
| assignment_id | assignor | task_id | assignee | 
+---------------+--------------------+----------+
|       1       |    a1    |    t1   |    x1    | 
+---------------+----------+---------+----------+
|       2       |    a1    |    t1   |    x2    | 
+---------------+----------+---------+----------+
当转让人删除受让人时,该表如下所示:

+---------------+----------+---------+----------+
| assignment_id | assignor | task_id | assignee | 
+---------------+--------------------+----------+
|       1       |    a1    |    t1   |    x1    | 
+---------------+----------+---------+----------+
|       2       |    a1    |    t1   |   null   | 
+---------------+----------+---------+----------+
现在,我需要一个查询,该查询仅当此特定任务id的每个记录在列中都有null值时才返回true。 到目前为止,我写的是:

SELECT DISTINCT task_id, nulls, total,

    (CASE
        WHEN nulls = total then true
        ELSE false
    END) unassigned
    
FROM

(
SELECT task_id, 
(SELECT count(*) FROM assignments b WHERE assignee IS NULL AND b.task_id = a.task_id) 'nulls',
(SELECT count(*) FROM assignments b WHERE b.task_id = a.task_id) 'total'

FROM assignments a 

WHERE assignee is NULL) c
结果是:

+--------------------------------------+
| task_id | nulls | total | unassigned | 
+--------------------------------------+
|    1    |   2   |   2   |     1      | 
+---------+-------+-------+------------+

对改进我的查询或完全替换它有什么建议吗?

如果我没有弄错,您可以使用聚合:

select assignment_id,
    count(*) - count(assignee) as nulls,
    count(*) as total,
    case when count(assignee) = 0 then 1 else 0 end as unassigned
from assignments
group by assignment_id
如果要筛选未分配的分配,则可以在查询末尾添加
having
子句:

having count(assignee) = 0

我认为您只需要两列:
task\u id
assignment
null
s的行数
因此,
按taskid分组
,并在
having
子句中设置条件:

select task_id, count(*) total
from assignments
group by task_id
having max(assignee) is null
条件
的max(assignment)为null
只返回
assignee
列中只有
null
s的
taskid
s