使用ibase查询的递归函数php

时间:2017-06-29 11:16:37

标签: php function firebird

我有一个函数可以通过某个文件的id构建一个路径,该函数可以正常工作,直到它抛出ibase_query错误。 这是功能:

function Build_Path($id,$database){
$path_query = "SELECT PATH_NAME,FATHER_ID,VOLUME_ID FROM PATHS WHERE PATH_ID = ".$id;
$query = ibase_query($database, $path_query);
while ($names = ibase_fetch_object($query)) {
    $path_volume_id = $names->VOLUME_ID;
    $name = $names->PATH_NAME;
    $father_id = $names->FATHER_ID;
    if ($name == "") {
        $volumes = ibase_query($database, "SELECT VOLUME_NAME FROM VOLUMES WHERE VOLUME_ID = " . $path_volume_id);
        while ($get_volume_name = ibase_fetch_object($volumes)) {
            return $get_volume_name->VOLUME_NAME;
        }
        ibase_free_result($volumes);
    } else {
        return Build_Path($father_id, $database) . "/" . $name;
    }
}
ibase_free_result($query);
ibase_close($database);
}

错误仅在路径号12999之后抛出,并且表示:

ibase_query(): too many open handles to database

错误被抛出一次然后查询没有收到任何结果,尽管我的数据库中有1500000个路径。

1 个答案:

答案 0 :(得分:3)

试试这个递归函数

WITH RECURSIVE hierarchy (PATH_ID, PARENT_ID, PATH_NAME) as (
   SELECT PATH_ID, PARENT_ID, PATH_NAME
   FROM PATHS
   WHERE PARENT_ID = -1

   UNION ALL

   SELECT PATH_ID, PARENT_ID, PATH_NAME
   FROM PATHS f
     JOIN hierarchy p ON p.PATH_ID = f.PARENT_ID
)
SELECT *
FROM hierarchy

编辑 发现firebird实际上是一个数据库引擎。每天学习一些东西

- 原始答案 -

为什么不使用加入?

SELECT VOLUMES.VOLUME_NAME FROM PATHS WHERE PATH_ID = :ID
left join PATHS as PATH_1 on PATHS.FATHER_ID = PATH_1.PATH_ID
left join PATHS as PATH_2 on PATH_1.FATHER_ID = PATH_2.PATH_ID
left join PATHS as PATH_3 on PATH_2.FATHER_ID = PATH_3.PATH_ID
left join PATHS as PATH_4 on PATH_3.FATHER_ID = PATH_4.PATH_ID
left join PATHS as PATH_5 on PATH_4.FATHER_ID = PATH_5.PATH_ID
left join PATHS as PATH_6 on PATH_5.FATHER_ID = PATH_6.PATH_ID
left join PATHS as PATH_7 on PATH_6.FATHER_ID = PATH_7.PATH_ID
left join PATHS as PATH_8 on PATH_7.FATHER_ID = PATH_8.PATH_ID
left join PATHS as PATH_9 on PATH_8.FATHER_ID = PATH_9.PATH_ID
left join PATHS as PATH_10 on PATH_9.FATHER_ID = PATH_10.PATH_ID
JOIN VOLUMES on (
     VOLUMES.VOLUME_ID = PATHS.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_1.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_2.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_3.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_5.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_6.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_7.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_8.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_9.VOLUME_ID
     OR VOLUMES.VOLUME_ID = PATH_10.VOLUME_ID
)
WHERE VOLUMES.VOLUME_NAME IS NOT NULL and VOLUMES.VOLUME_NAME != ""