चरण 0:एक ऐसा दृश्य बनाएं जो सभी पड़ोसी जोड़े दिखाता हो
CREATE VIEW neighbour AS
( SELECT loc1.id AS a
, loc2.id AS b
FROM locations loc1
, locations loc2
WHERE FIND_IN_SET(loc1.id, loc2.neighbours)>0
OR FIND_IN_SET(loc2.id, loc1.neighbours)>0
) ;
चरण 1:1 गहराई वाले पड़ोसियों को ढूंढें
SELECT b AS depth1
FROM neighbour
WHERE a = 1; <-- for root with id=1
चरण 2:2 गहराई वाले पड़ोसियों को ढूंढें
SELECT DISTINCT d2.b AS depth2
FROM neighbour d1
JOIN neighbour d2
ON d1.b = d2.a
AND d2.b != 1
WHERE d1.a = 1 <-- for root with id=1
AND d2.b NOT IN
( SELECT b AS depth1 <- depth1 subquery
FROM neighbour
WHERE a = 1 <-- for root with id=1
)
;
चरण 3:3 गहराई वाले पड़ोसियों को ढूंढें
SELECT d3.b as depth3
FROM neighbour d1
JOIN neighbour d2
ON d1.b = d2.a
AND d2.b != 1
AND d2.b NOT IN
( SELECT b as depth1
FROM neighbour
WHERE a = 1
)
JOIN neighbour d3
ON d2.b = d3.a
AND d3.b != 1
WHERE d1.a = 1
AND d3.b NOT IN
( SELECT b as depth1
FROM neighbour
WHERE a = 1
)
AND d3.b NOT IN
( SELECT d2.b AS depth2
FROM neighbour d1
JOIN neighbour d2
ON d1.b = d2.a
AND d2.b != 1
WHERE d1.a = 1
AND d2.b NOT IN
( SELECT b AS depth1
FROM neighbour
WHERE a = 1
)
)
;
जैसा कि आप देख सकते हैं, वृद्धि क्वेरी लाइनों की संख्या के लिए घातीय है, इसलिए मैं स्तर 4 की कोशिश नहीं करूंगा।