具有递归 CTE 的查询可以完成这项工作。需要 PostgreSQL 8.4或更高版本:
WITH RECURSIVE next_in_line AS ( SELECt u.id AS unit_id, u.parent_id, a.unit_id AS acl FROM unit u LEFT JOIN acl a ON a.unit_id = u.id UNIOn ALL SELECt n.unit_id, u.parent_id, a.unit_id FROM next_in_line n JOIN unit u ON u.id = n.parent_id AND n.acl IS NULL LEFT JOIN acl a ON a.unit_id = u.id )SELECt unit_id, aclFROM next_in_lineWHERe acl IS NOT NULLORDER BY unit_id
第二回合的休息条件
UNIOn是
n.acl IS NULL。这样,一旦
acl找到,查询就会停止遍历树。
最后,
SELECT我们只返回
acl找到an 的行。瞧。
顺便说一句:使用通用的、非描述性的
id作为列名是一种反模式。可悲的是,一些 ORM 默认情况下会这样做。调用它
unit_id,您不必一直在查询中使用别名。



