我有一个与自身具有ManyToMany关系的表。 因此,我的H2-Database中有两个表:
supporting_asset: supporting_asset_dependencies:
id | provided_csc dependencies_id | supporting_assets_id
------------------ ---------------------------------------
1 | A1 1 | 2
2 | A3 1 | 3
3 | A2
我有一个计算出的属性“ minCSC”,要计算它,我使用了@Formula批注:
@Formula(value="(Select min(sa.provided_csc) from supporting_asset_dependencies sad right join supporting_asset sa on sa.id = sad.dependencies_id where sad.supporting_assets_id = id group by id)")
这很好用,但是依赖的资产可以拥有它们自己的依赖项。有了这个,我得到了一个多层次的依赖树。我的目标是从此树中获取最小的csc。
我尝试过:
WITH RECURSIVE tree(id, provided_csc, dep_id)
AS (SELECT sa.id, sa.provided_csc, sad.supporting_assets_id
FROM supporting_asset_dependencies AS sad
JOIN supporting_asset AS sa
ON sa.id=sad.dependencies_id
WHERE sad.supporting_assets_id=2
UNION ALL
SELECT child.id, child.provided_csc, childd.supporting_assets_id
FROM supporting_asset_dependencies AS childd
JOIN supporting_asset AS child
ON child.id=childd.dependencies_id
JOIN tree ON childd.supporting_assets_id=tree.id )
SELECT min(provided_csc)
FROM tree
但是我收到“ SQL语句中的语法错误”。该公式似乎被计算为:
(SUPPORTING2_.WITH[*] TREE(SUPPORTING2_.ID, SUPPORTING2_.PROVIDED_CSC, SUPPORTING2_.DEP_ID) AS ( ..
.. ) SELECT MIN(SUPPORTING2_.PROVIDED_CSC) FROM TREE) AS FORMULA0_1_,
它似乎不知道“ with recursive”命令,并试图将其作为表的字段来查找。
我该如何更改查询才能使其正常工作,或者有另一种方法可以实现我想要的?
---更新--- 我稍微更改了查询,然后在DB Fiddle上将其用于SQLite数据库。它似乎也可以在h2网络控制台中工作。