postgrePostgres SQL递归查询



我正在使用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查询
非常感谢!

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;

相关内容

  • 没有找到相关文章

最新更新