仅当所有记录在特定列中都为 null 时,查询才返回 true
Posted
技术标签:
【中文标题】仅当所有记录在特定列中都为 null 时,查询才返回 true【英文标题】:Query to return true only if all of its records have null in a specific column 【发布时间】:2020-09-16 13:38:04 【问题描述】:假设有一个表assignments,它的列是
assignment_id 转让人 task_id 受让人assignor 可以将相同的 task_id 分配给多个受让人。 目前,我有一个分配给 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 |
+---------------+----------+---------+----------+
现在,我需要一个查询,该查询仅在此特定 task_id 的每条记录在受理人列中具有空值时才返回真。 到目前为止我写的:
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 |
+---------+-------+-------+------------+
关于改进我的查询或完全替换它的任何建议?
【问题讨论】:
【参考方案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
【讨论】:
【参考方案2】:我认为您只需要 2 列:task_id
和 assignee
中 null
s 的行数。
所以group by taskid
并在having
子句中设置条件:
select task_id, count(*) total
from assignments
group by task_id
having max(assignee) is null
条件having max(assignee) is null
仅返回在assignee
列中只有null
s 的taskid
s。
【讨论】:
以上是关于仅当所有记录在特定列中都为 null 时,查询才返回 true的主要内容,如果未能解决你的问题,请参考以下文章