3

I have this table:

Content:
- id
- parent_id
- slug
- creation_date

parent_id is a foreign key pointing to the same table (content.id).

I want to select all the rows in the table that are children of a parent_id in the same table. I would like the parent row to be returned too.

Right now I have these two queries, both of which work only returning the child rows:

SELECT a.* 
FROM content a 
JOIN content b ON a.parent_id = b.id
WHERE b.slug = 'some-slug'
ORDER BY creation_date

and:

SELECT content.* 
FROM content 
WHERE content.parent_id = (SELECT id FROM content WHERE slug= 'some-slug')
ORDER BY creation_date

How can I return the child rows as well as the parent row ordered by creation_date?

Thanks!

SrgHartman
  • 651
  • 2
  • 8
  • 23

1 Answers1

3
select  child.*
from    Content child
join    Content parent
on      child.parent_id = parent.id
where   parent.slug = 'some-slug'
union all
select  parent.*
from    Content parent
where   parent.slug = 'some-slug'
order by
        creation_date
Andomar
  • 232,371
  • 49
  • 380
  • 404