我有这张表:
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 排序的子行和父行?
谢谢!
最佳答案
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
关于mysql - 自连接查询 : how to return children and parent row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967493/