sql >> Databasteknik >  >> RDS >> PostgreSQL

SQL-fråga:Hämta ordnade rader från en tabell

Använd en rekursiv fråga (PostgreSQL version 8.4 eller senare):

/* test data:
CREATE TABLE foo (id, r_id, a_id, p_id) AS
    SELECT  1,9,9,0
    UNION ALL SELECT 2,9,105,108
    UNION ALL SELECT 3,9,102,9
    UNION ALL SELECT 4,9,106,105
    UNION ALL SELECT 5,9,108,102        
;
*/

-- the query you need:
WITH RECURSIVE sub(s_id, s_r_id, s_a_id, s_p_id, row) AS (
    SELECT id, r_id, a_id, p_id, 1 AS row FROM foo WHERE p_id = 0
UNION ALL
    SELECT id, r_id, a_id, p_id, (row + 1)  FROM foo JOIN sub ON s_a_id = p_id
)
SELECT * FROM sub ORDER BY row;


  1. Hur konfigurerar jag allocationSize inom persistence.xml istället för Entity

  2. Hibernate mysql innodb

  3. Uttalas det "S-Q-L" eller "Sequel"?

  4. Reninstallera VestaCP