Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Permintaan pencarian pertama yang luas di MySQL?

langkah 0:Buat tampilan yang menampilkan semua pasangan tetangga

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

langkah 1:Temukan tetangga dengan kedalaman 1

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

langkah 2:Temukan tetangga dengan kedalaman 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
      )
;

langkah 3:Temukan tetangga dengan kedalaman 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
            )
     )
;

Seperti yang Anda lihat, pertumbuhannya eksponensial untuk jumlah baris kueri, jadi saya tidak akan mencoba level 4.



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara menampilkan rentang jam

  2. kelas tidak ditemukan pengecualian com.mysql.jdbc.driver

  3. dapatkah couchdb melakukan perulangan?

  4. sql/mysql filter hanya menyertakan nilai maksimal

  5. Urutan MySQL berdasarkan Rand() dikelompokkan berdasarkan hari