我有两张桌子,结构如下:
表1 。交易数据表
trx id.
1
2
3
4
5..etc
表2 表2具有如下的父子关系。
id subject_id (Child) object_id (Parent)
1 2 1
2 3 1
3 4 1
4 5 1
现在使用上面的表格,预期输出如下:
1
2
3
4
5
请让我知道如何实现同样的目标。我需要从表1中获取详细信息以及父级及其层次结构中的所有子级。我只有一个级别的层次结构。
答案 0 :(得分:0)
由于您只有一个级别的层次结构,因此只需正确排序结果即可使其正常工作。试试这个:
select obj.object_id, t.*
from
(
select
object_id,
object_id as parent_id
from table2
union
select
subject_id as object_id,
object_id as parent_id
from table2
) obj
inner join table1 t
on t.id = obj.object_id
order by
obj.parent_id,
case when obj.object_id = obj.parent_id then 0 else 1 end,
obj.object_id
答案 1 :(得分:0)
我对 @a_horse ...
的评论略有不同select * from table1
where id in
(select object_id from table2
union all
select subject_id from table2)
order by id;
按预期
1
2
3
4
5
如果要约束父节点,只需在子查询中添加WHERE谓词。