从 child id in mysql 获取 parent id 的详细信息

Getting the details of parent id from child id in mysql

我正在创建一个消息传递应用程序。我有一个table和一个parent的id来标识它是一个child的主键消息。现在我想获取 parent 的详细信息,并且我有 child 的可用 ID。 比如选择条件 id = 28 的 parent = 0 的值。

这是我的 table.

的结构和示例数据
                     message_tbl
 id          message          date               parent_msg
 27          hello     2020-05-24 15:03:40           0
 28          world     2020-05-24 15:04:17           27

我想要这样的结果:

27          hello     2020-05-24 15:03:40           0

这是结构的 sqlfiddle: http://sqlfiddle.com/#!9/2b18d2

对于单级关系,自联接可以:

select mp.*
from message_tbl mp
inner join message_tbl mc on mc.parent_msg = mp.id
where mc.id = 28

如果级别数可变,则可以使用递归查询(仅在 MySQL 8.0 中可用):

with recursive cte as (
    select * from message_tbl where id = 28
    union all
    select m.*
    from message_tbl m
    inner join cte c on c.parent_msg = m.id
)
select * from cte where parent_msg = 0