【问题标题】:Getting the details of parent id from child id in mysql从mysql中的子ID获取父ID的详细信息
【发布时间】:2020-05-25 01:14:18
【问题描述】:

我正在创建一个消息传递应用程序。我有一个带有父 ID 的表来标识它是主键消息的子级。现在我想获取父母的详细信息,并且我有一个可用的孩子 id。 类似于在条件 id = 28 的情况下选择 parent = 0 的值。

这是我的表的结构和示例数据。

                     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

【问题讨论】:

    标签: mysql sql join select recursive-query


    【解决方案1】:

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

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

    如果您有可变数量的级别,那么您可以使用递归查询(仅在 MyQSL 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
    

    【讨论】:

    • 谢谢...如果我有很多数据,你觉得这样好吗?
    猜你喜欢
    • 2022-11-27
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2011-12-11
    相关资源
    最近更新 更多