我有兩個MySQL表:節點和關係查找節點之間的路徑與SQL
CREATE TABLE `nodes` (
`id` int(10) unsigned NOT NULL auto_increment,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `relations` (
`node_id` int(10) unsigned NOT NULL,
`related_node_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
比方說,有四行中的節點:節點1和2共享的關係,2和3,1和4, 4和3
INSERT INTO `relations` VALUES (1, 2);
INSERT INTO `relations` VALUES (2, 3);
INSERT INTO `relations` VALUES (1, 4);
INSERT INTO `relations` VALUES (4, 3);
是否有任何算法來獲取相關節點之間的路徑?像
+---------+------------------+---------+
| node_id | related_node_id | route |
+---------+------------------+---------+
| 1 | 2 | 1/2 |
| 2 | 3 | 2/3 |
| 1 | 4 | 1/4 |
| 4 | 3 | 4/3 |
| 1 | 3 | 1/2/3 |
| 1 | 3 | 1/4/3 |
+---------+-----------+------+---------+