I've added a few more rows just to cover all cases.
drop table if exists mytable;
create table if not exists mytable
(
id int,
parent_id int,
created_at date
);
insert into mytable values
(24, 0, '20170101'),
(25, 0, '20170101'),
(26 ,25, '20170101'),
(27, 25, '20170102'),
(28, 0, '20170102'),
(29, 28, '20170102'),
(30, 28, '20170103'),
(31, 20, '20170103');
select id, parent_id
from mytable
where (parent_id = 0 and not exists (select 1
from mytable m2
where m2.parent_id = mytable.id))
or
(id = (select m3.id
from mytable m3
inner join mytable m4
on m4.parent_id = 0
where m4.id = mytable.parent_id
and m3.parent_id = m4.id
order by m3.created_at desc
limit 1))
;
This is the result:
| id | parent_id |
|----|-----------|
| 24 | 0 |
| 27 | 25 |
| 30 | 28 |
Rextester here
First condition select all rows where parent_id=0
and not exists any children:
where (parent_id = 0 and not exists (select 1
from mytable m2
where m2.parent_id = mytable.id))
Second condition select all rows where its parent is at first level. parent_id=0
ordered by created_at desc. (Limit 1 on main query)
select m3.id, m3.parent_id, m3.created_at
from mytable m3
inner join mytable m4
on m4.parent_id = 0
and m3.parent_id = m4.id
order by m3.created_at desc;
This returns this rows:
| id | parent_id | created_at |
|----|-----------|---------------------|
| 30 | 28 | 03.01.2017 00:00:00 |
| 27 | 25 | 02.01.2017 00:00:00 |
| 29 | 28 | 02.01.2017 00:00:00 |
| 26 | 25 | 01.01.2017 00:00:00 |