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

时间:2018-05-25 16:41:30

标签: mysql rdbms

假设我有一个草稿表:每个Parent都有一个唯一的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.

UPDATE :我想要父行,而不是父ID。

2 个答案:

答案 0 :(得分:1)

怎么样

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

我假设你想要返回parent_id而不是id,因为你的描述暗示前者,而你的实际sql暗示后者。

答案 1 :(得分:1)

这应该有效:

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