Find path between nodes with SQL

I have two mysql tables: nodes and relationships

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;

Let's say that there are four lines in the nodes: Node 1 and 2 share the relation, 2 and 3, 1 and 4, 4 and 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);

Is there any algorithm for getting paths between related nodes? how

+---------+------------------+---------+
| 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   |
+---------+-----------+------+---------+
+3
source share
2 answers

There is MySQLno easy way to do this in vanilla .

You can install OQGRAPH(this is a plug-in storage engine intended for storing graphs), create a graph table in it and ask this query:

SELECT  *
FROM    oqtable
WHERE   latch = 1
        AND origid = 1
        AND destid = 3

which will use Dijkstraโ€™s algorithm to find the shortest path between 1and 3.

+2
source

, . SQL, , - - , MySQL.

+1

Source: https://habr.com/ru/post/1735220/


All Articles