sql >> Database teknologi >  >> RDS >> PostgreSQL

PostgreSQL:Find tilladelse til element, kryds op til rod

Du kan bruge en RECURSIVE CTE til dette:

WITH RECURSIVE Perms(ID, Name, ParentID, CanRead, CanWrite, CanDelete) AS ( SELECT i.ID, i.Name, l.LID AS ParentID, p.CanRead, p.CanWrite, p.CanDelete FROM Item AS i LEFT JOIN Permission AS p ON i.ID = p.ID LEFT JOIN Links AS l ON i.ID = l.ID ), GET_PERMS(ID, ParentID, CanRead, CanWrite, CanDelete) AS ( -- Anchor member: Try to get Read/Write/Delete values from Permission table SELECT ID, ParentID, CanRead, CanWrite, CanDelete FROM Perms WHERE ID = 3 UNION ALL -- Recursive member: terminate if the previous level yielded a `NOT NULL` result SELECT p.ID, p.ParentID, p.CanRead, p.CanWrite, p.CanDelete FROM GET_PERMS AS gp INNER JOIN Perms AS p ON gp.ParentID = p.ID WHERE gp.CanRead IS NULL ) SELECT CanRead, CanWrite, CanDelete FROM GET_PERMS WHERE CanRead IS NOT NULL

Den RECURSIVE CTE afsluttes, når en Permission posten er blevet hentet fra databasen.

Demo her



  1. Ugyldigt forsøg på at få adgang til feltet før kald read()

  2. Valg af en kolonne, der opfylder mange betingelser i forskellige poster

  3. Husk dette, når du formaterer en TIME-datatype i SQL Server (T-SQL)

  4. markøren i en trigger