使用闭包表获取连接选择中的最低层次结构子项

时间:2017-07-12 18:35:54

标签: mysql sql tree hierarchical-data transitive-closure-table

我有一个闭包表HIERARCHY

ancestor | descendant | depth
100      | 100        | 0
2        | 100        | 1
3        | 100        | 2
4        | 100        | 3

和连接表属性

id       | key        | value
4        | action     | DEFAULT
4        | duration   | PT1H
100      | action     | OVERRIDE
100      | duration   | PT1M

我可以使用查询

获取整个子树
  SELECT id, key, value
    FROM hierarchy, properties
   WHERE id = ancestor
     AND descendant = 100
ORDER BY depth

获得最低层次结构成员的最简单/最快方法是什么?,即。有min(depth)

100      | action     | OVERRIDE
100      | duration   | PT1M

我仍然需要保留层次结构,这意味着如果在查询中找不到100,则会显示4

换句话说,我试图找到具有最低深度的树成员的所有行,可能没有在WHERE子句中重复查询

数据库是当前完全发布的mysql,即。 5.7

1 个答案:

答案 0 :(得分:0)

http://sqlfiddle.com/#!6/ce317/16

With A as(
    Select 
      id, _key, value, depth
    From 
      hierarchy
    Join
      properties
    On id = ancestor And descendant = 100
    ) 
Select id, _key, value from A
Where depth = (select min(depth) from A)

对于MySQL,请使用临时表...

CREATE TEMPORARY TABLE A AS 
(
    Select 
      id, _key, value, depth
    From 
      hierarchy
    Join
      properties
    On id = ancestor And descendant = 100
); 
Select id, _key, value from A
Where depth = (select min(depth) from A);

或者,希望MySQL能够缓存... http://sqlfiddle.com/#!9/d2350e/1

Select id, _key, value
From
(
    Select id, _key, value, depth From hierarchy Join properties On id = ancestor And descendant = 100
) B
Join
    (
      Select min(A.depth) min
      From
      (
        Select id, _key, value, depth From hierarchy Join properties On id = ancestor And descendant = 100
      ) A
    )C
On
  B.depth = C.min

关于缓存。 https://dba.stackexchange.com/questions/44266/does-mysql-cache-queries