自联接查询:如何返回子进程和父进程?

时间:2015-01-15 15:54:33

标签: mysql sql self-join

我有这张桌子:

Content:
- id
- parent_id
- slug
- creation_date

parent_id是指向同一个表(content.id)的外键。

我想在表中选择同一个表中parent_id的子项的所有行。我也希望返回父行。

现在我有这两个查询,这两个查询只返回子行:

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

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

如何返回子行以及creation_date命令的父行?

谢谢!

1 个答案:

答案 0 :(得分:2)

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