Postgres SQL递归查询

时间:2016-08-04 06:25:42

标签: sql postgresql recursive-query

我正在使用PostgreSQL 有两个表:图层和图像

LAYERS (layer_id  varchar PRIMARY KEY,
        parent_id varchar REFERENCES LAYERS(layer_id))

IMAGES (image_id  varchar UNIQUE, REFERENCES LAYERS(layer_id))

in LAYERS table: 1->2->3->4->5->6 (1 is the parent of 2)
in IMAGES table: 1,2,5,6

现在我想知道,哪个图像是图像5的最近父图像? 答案是图像2

如何编写这样的SQL查询? 非常感谢!

1 个答案:

答案 0 :(得分:0)

WITH RECURSIVE parents(id) AS(
   SELECT parent FROM layers WHERE layerid = '5'
   UNION
   SELECT layers.parent FROM parents, layers WHERE layers.layerid = parents.id
      AND parents.id NOT IN (SELECT imageid FROM images)
) 
SELECT imageid FROM parents, images WHERE images.imageid = parents.id;