'Mysql multiple connection tree/neural structure, get all connections recursive

I am trying to figure out how to get the connections of a structure like:

id  connection    
...
74          0 
74         76
74         83 
76         79
79         85
85          0
...

What I would need is to get all connections of 74, so 76, 83 but also all connections of the 76 and 83 recursively.

I managed to do this via backend but its performance will be affected in time.

How can I write this in mysql in order to get something like? [76, 79, 85, 83] I am using mysql 8

sql fiddle

CREATE TABLE IF NOT EXISTS `connections` (
  `_id` int(6) unsigned NOT NULL AUTO_INCREMENT,
  `id` int(6) unsigned NOT NULL,
  `connection_id` int(6) unsigned NOT NULL,
  PRIMARY KEY (`_id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `connections` (`id`, `connection_id`) VALUES
  (74, 0),
  (74, 76),
  (74, 83),
  (76, 79),
  (79, 85),
  (85, 0);

I am using Mariadb 10.1.48, and the desired output:

id 
76  
83  
79 
85
   

EDIT I tried writing it like:

SELECT T2.* 
FROM ( 
    SELECT 
        @r AS id_, 
        (SELECT @r := connection_id FROM connections WHERE id = id_) AS connection_id, 
        @l := @l + 1 AS lvl 
    FROM 
        (SELECT @r := 74, @l := 0) vars, 
        connections h 
    WHERE @r <> 0) T1 
JOIN connections T2 
ON T1.id_ = T2.id 
ORDER BY T1.lvl DESC 

But I get only the first level of the connections:

Also tried as suggested with CTE but don't know how to get just the connections of one of the items... ex.: 74

WITH RECURSIVE cte (id_, connection_id_) AS
(
  SELECT id, connection_id FROM connections WHERE id = (SELECT 
MIN(id) FROM connections)
  UNION ALL
  SELECT 
    c.connection_id_, t.connection_id
  FROM
    cte c
  JOIN connections t
  ON c.connection_id_ = t.id
)
SELECT * FROM cte;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source