根据某个 parent id 获取 ids 列表,在 child table 中没有 2 个特定行
Getting a list of ids based on a certain parent id not having 2 specific rows in the child table
光是这个标题就很难打出来。
我需要一些帮助来安排查询。假设以下设置:
1 'parent' table
1 'child' table
这是一个例子:
id | parent_id | type
---------------------
1 | 1 | 'BAND'
2 | 1 | 'AUTHOR'
3 | 2 | 'BAND'
4 | 3 | 'BAND'
5 | 3 | 'AUTHOR'
6 | 4 | 'BAND'
7 | 5 | 'BAND'
8 | 5 | 'AUTHOR'
创建 'child' 时,默认情况下应该接收 2 行,除了 1 个字段 "type" 字段外,每行都相同。类型是一个 varchar 字段,包含 'BAND' 或 'AUTHOR'
过去只有'BAND'。进行更新后,结果发现执行此操作的脚本遗漏了一些 ID,现在有些 children 同时拥有 'BAND' 和 'AUTHOR',但有些人仍然停留在只有 'BAND'
所以现在我需要找到 'child' table 中不存在此组合的所有 ID。
因此在示例中,结果应为 id 3 和 6。
我为此绞尽脑汁,一直想不通。任何帮助将不胜感激。
您可以通过条件聚合轻松获取父 ID:
select parent_id, min(id) as id
from example
group by parent_id
having sum(case when type = 'BAND' then 1 else 0 end) = 0 or
sum(case when type = 'AUTHOR' then 1 else 0 end) = 0;
或者,也许更简单:
select parent_id, min(id) as id
from example
group by parent_id
having count(distinct type) = 1;
光是这个标题就很难打出来。
我需要一些帮助来安排查询。假设以下设置:
1 'parent' table
1 'child' table
这是一个例子:
id | parent_id | type
---------------------
1 | 1 | 'BAND'
2 | 1 | 'AUTHOR'
3 | 2 | 'BAND'
4 | 3 | 'BAND'
5 | 3 | 'AUTHOR'
6 | 4 | 'BAND'
7 | 5 | 'BAND'
8 | 5 | 'AUTHOR'
创建 'child' 时,默认情况下应该接收 2 行,除了 1 个字段 "type" 字段外,每行都相同。类型是一个 varchar 字段,包含 'BAND' 或 'AUTHOR'
过去只有'BAND'。进行更新后,结果发现执行此操作的脚本遗漏了一些 ID,现在有些 children 同时拥有 'BAND' 和 'AUTHOR',但有些人仍然停留在只有 'BAND'
所以现在我需要找到 'child' table 中不存在此组合的所有 ID。
因此在示例中,结果应为 id 3 和 6。
我为此绞尽脑汁,一直想不通。任何帮助将不胜感激。
您可以通过条件聚合轻松获取父 ID:
select parent_id, min(id) as id
from example
group by parent_id
having sum(case when type = 'BAND' then 1 else 0 end) = 0 or
sum(case when type = 'AUTHOR' then 1 else 0 end) = 0;
或者,也许更简单:
select parent_id, min(id) as id
from example
group by parent_id
having count(distinct type) = 1;