我正在尝试将专有的Oracle CONNECT BY
查询转换为将在H2上运行的标准SQL查询,并以相同的顺序生成相同的数据。
这是Oracle查询,有效:
SELECT id, name, parent
FROM myschema.mytable
START WITH id = 1
CONNECT BY PRIOR id = parent
这就是我的想法 - 然而,它在ResultSet
中没有返回任何行。
WITH RECURSIVE T(id, name, parent, path) AS (
SELECT id, name, '' AS parent, id AS path
FROM myschema.mytable WHERE id = 1
UNION ALL
SELECT ou.id, ou.name, ou.parent,
(T.path + '.' + CAST (ou.id AS VARCHAR)) AS path
FROM T INNER JOIN myschema.mytable AS ou ON T.id = ou.parent
) SELECT id, name, parent FROM T ORDER BY path
表中存在初始行和相关行。
我没有使用H2的Oracle兼容模式(顺便说一下,它不支持CONNECT BY)。
答案 0 :(得分:3)
以下适用于我,包括H2和PostgreSQL(this you can test online using the SQL Fiddle)。我不得不做出一些改变和假设(见下文):
create table mytable(id int, name varchar(255), parent int);
insert into mytable values(1, 'root', null), (2, 'first', 1),
(3, 'second', 1), (4, '2b', 3);
WITH RECURSIVE T(id, name, parent, path) AS (
SELECT id, name, 0 AS parent,
cast(id as varchar) AS path
FROM mytable WHERE id = 1
UNION ALL
SELECT ou.id, ou.name, ou.parent,
(T.path || '.' || CAST (ou.id AS VARCHAR)) AS path
FROM T INNER JOIN mytable AS ou ON T.id = ou.parent
) SELECT id, name, parent, path FROM T ORDER BY path
的变化:
id
和parent
是整数。因此,我必须在第一个选择中使用cast(id as varchar)
。 +
替换为||
。 0 AS parent
。答案 1 :(得分:0)
这似乎是Anorm数据库访问库或JDBC驱动程序没有正确替换查询参数的问题(查询替换未在问题中显示,因为我认为它不相关)。