rdbms—仅在mysql查询中删除所有子项时检索父行

zengzsys  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(232)

假设我有一个草稿表:每个父表都有一个唯一的id,并且它的父列设置为null。
草稿:

id |  parent_id | is_deleted
--- ------------ ------------
 1 |  null      | 0
 2 |    1       | 0
 3 |    1       | 1
 4 |   null     | 0
 5 |    4       | 1
 6 |    4       | 1
 7 |    4       | 0
 8 |   null     | 0
 9 |    8       | 1

现在我想得到一个父母名单,他们所有的删除只。

select id 
from draft
where id in (
  select parent_id
  from draft
  where id in (1, 2, 3, 5, 7, 9)
  group by parent_id
  having sum(case when is_deleted 0 then 1 else 0) <= 0
)
where is_deleted = 0;

这里的问题是它总是返回父级的1、4和8。但它应该只返回8。
更新:我想要父行,而不是父id。

xkftehaa

xkftehaa1#

怎么样

select a.*
  from draft a
  join
    (select distinct parent_id
    from draft d
    where (select count(*) from draft e 
           where e.is_deleted = 0 and e.parent_id = d.parent_id) = 0) b
  on a.id=b.parent_id

我假设您希望返回父\ id而不是id,因为您的描述暗示了前者,而实际的sql暗示了后者。

bvpmtnay

bvpmtnay2#

这应该起作用:

select * from draft
where id in
(
    select parent_id from draft a where is_deleted = 1
    and not exists
    (select 1 from draft b where a.parent_id = b.parent_id and is_deleted = 0)
)

你也可以使用 JOIN 而不是 IN ```
select draft.* from draft
join(
select parent_id from draft a where is_deleted = 1
and not exists
(select 1 from draft b where a.parent_id = b.parent_id and is_deleted = 0)
) p on parent.id = p.parent_id

相关问题