-1

我有一个封闭表 HIERARCHY

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

和一个连接表 PROPERTIES

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

4

1 回答 1

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

于 2017-07-13T11:39:30.427 回答