2階層構造のテーブルで親を求める前提階層構造を表すテーブルtblを考える。 スキーマ
データid | p_id | name ----+------+------ 1 | 1 | A 2 | 2 | B 10 | 1 | A1 11 | 1 | A2 12 | 1 | A3 13 | 2 | B1 14 | 2 | B2 CREATE TABLE tbl (id int, p_id int, name text) ; INSERT INTO tbl VALUES ( 1,1,'A' ), ( 2,2,'B' ); INSERT INTO tbl VALUES ( 10,1,'A1' ) , ( 11,1,'A2' ) , ( 12,1,'A3' ); INSERT INTO tbl VALUES ( 13,2,'B1' ), ( 14,2,'B2' ); 親IDの名前を求めるSELECT t1.id, t1.p_id, t1.name, t2.name FROM tbl t1 JOIN tbl t2 ON t1.p_id = t2.id ORDER BY t1.id; id | p_id | name | name ----+------+------+------ 1 | 1 | A | A 2 | 2 | B | B 10 | 1 | A1 | A 11 | 1 | A2 | A 12 | 1 | A3 | A 13 | 2 | B1 | B 14 | 2 | B2 | B |
|