我有以下表格架构:
create table location_master (id serial,name character varying,parent_id integer);
INSERT INTO location_master (name,parent_id)
VALUES
('Bombay',1)
, ('Ahmedabad',1)
, ('Surat',1)
, ('Vapi',3)
, ('Navarangpura',2);
从上表中我想找到从源id = 1
到目的地id = 4
的路径。所以预期的结果如下:
目的地id = 4
。哪个有parent_id = 3
。单词id = 3
上有parent_id = 1
等等。
例:
用户希望将包裹从id = 1
发送到id = 4
。宗地的路由路径由此表决定。当用户选择源id = 1
和目标id = 4
时,查询会自动从子父关系中找到路由。包裹将通过1,3,4
路径。
我为此尝试了SELF JOIN,但没有得到预期的结果。
答案 0 :(得分:1)
Thanks joop. I search for Recursive Query and got the solution as I want:
WITH RECURSIVE demo AS (
SELECT parent_id
FROM location_master
WHERE id = <destination_id>
UNION ALL
SELECT a.parent_id
FROM location_master a
JOIN demo b ON(a.id = b.parent_id))
SELECT DISTINCT location_master.* FROM location_master JOIN demo
on location_master.id = demo.parent_id WHERE demo.parent_id != 0
UNION
SELECT location_master.* FROM location_master WHERE id = <destination_id>
ORDER BY id ;