如何查找消息链(MySQL中的分层查询)?
我有一个包含以下约束的消息表: -Each message have their own ID. -Each message belongs to a message type. -Each message can be a child of other message. -A parent message can be a parent of different type of messages. -The depth of hierarchy is unknown. 有人提供了这个解决方案,但我不知道它是否适用于我的情况如何查找消息链(MySQL中的分层查询)?,mysql,sql,Mysql,Sql,我有一个包含以下约束的消息表: -Each message have their own ID. -Each message belongs to a message type. -Each message can be a child of other message. -A parent message can be a parent of different type of messages. -The depth of hierarchy is unknown. 有人提供了这个解决方
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/
那么,在Mysql中查找祖先/后代消息链的最佳方法是什么?由于Mysql有限的SQL功能,您唯一的选择是编写存储过程或在应用程序中使用代码。u表示此解决方案使用嵌套集模型 Extra Constraint: -There is no such case that "1 child belongs to many parents". That is each message must belongs to Just 1 parent or belongs to NO parent (ie parentMessageID is NULL) -Parent child relationship doesn't go to the right order from top down. Ex, look at the above table, messageID "3" is a child of the below messageID "8". +--------------+---------------+-------------+------------------+ | messageText | messageType | messageID | parentMessageID | +--------------+---------------+-------------+------------------+ | msg text 1 | 1 | 1 | NULL | | msg text 2 | 1 | 2 | 1 | | msg text 5 | 2 | 5 | 2 | | msg text 7 | 3 | 7 | 5 | +--------------+---------------+-------------+------------------+ +--------------+---------------+-------------+------------------+ | messageText | messageType | messageID | parentMessageID | +--------------+---------------+-------------+------------------+ | msg text 8 | 3 | 8 | NULL | | msg text 3 | 1 | 3 | 8 | +--------------+---------------+-------------+------------------+ +--------------+---------------+-------------+------------------+ | messageText | messageType | messageID | parentMessageID | +--------------+---------------+-------------+------------------+ | msg text 8 | 3 | 8 | NULL | | msg text 3 | 1 | 3 | 8 | | msg text 9 | 1 | 9 | 8 | +--------------+---------------+-------------+------------------+ +--------------+---------------+-------------+------------------+ | messageText | messageType | messageID | parentMessageID | +--------------+---------------+-------------+------------------+ | msg text 2 | 1 | 2 | 1 | | msg text 5 | 2 | 5 | 2 | | msg text 7 | 3 | 7 | 5 | +--------------+---------------+-------------+------------------+
select messageText, messageType, @pv:=parentMessageID as 'parentMessageID' from table1
join
(select @pv:=2)tmp
where messageID=@pv
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/