sql >> Database >  >> RDS >> Mysql

Breedte eerste zoekopdracht in MySQL?

stap 0:maak een weergave die alle buurparen toont

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
) ;

stap 1:Zoek buren met diepte 1

SELECT b AS depth1
FROM neighbour
WHERE a = 1;               <-- for root with id=1

stap 2:Zoek buren met diepte 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
      )
;

stap 3:Zoek buren met diepte 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
            )
     )
;

Zoals je kunt zien, is de groei exponentieel voor het aantal vraagregels, dus ik zal het niveau 4 niet proberen.



  1. Hoe Distributed AD te gebruiken om de patchtijd in Oracle EBS te verkorten

  2. Verschil tussen ANSI- en Unicode-stuurprogramma's van MySQL

  3. Hoe de mysql-container initialiseren wanneer deze op Kubernetes is gemaakt?

  4. Gegevens afgekapt voor kolom 'xxxx' in rij 1