PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Kondisi berhenti CTE rekursif untuk loop

WITH RECURSIVE paths AS (
    -- For simplicity assume node 1 is the start
    -- we'll have two starting nodes for data = 1 and 2
    SELECT DISTINCT
        src           as node
        , data        as data
        , 0           as depth
        , src::text   as path
        , ''          as edgeAdded   
    FROM edges
    WHERE
        src = 1

    UNION ALL

    SELECT DISTINCT
        edges.dst
        , edges.data
        , depth + 1
        , paths.path || '->' || edges.dst::text
        , edges.src::text || '->' || edges.dst::text
    FROM paths
    JOIN edges ON edges.src = paths.node AND edges.data = paths.data
    AND NOT paths.path LIKE '%' || edges.dst::text || '%' 
        -- AND eliminate loops?
)
SELECT * FROM paths;

Di sini dengan kondisi AND NOT paths.path LIKE '%' || edges.dst::text || '%' kami menghindari tepi belakang yang akan mengarah ke loop.
http:/ /www.sqlfiddle.com/#!12/086ee/1



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. NULL vs. `infinity` dalam jenis rentang PostgreSQL

  2. SQL mengeluarkan data dari BEGIN; ...; AKHIR; blokir dengan python

  3. Bagaimana cara menutup koneksi idle di PostgreSQL secara otomatis?

  4. Bagaimana cara menghasilkan nomor seri dalam kueri?

  5. Memilih baris acak