从当前子ID PHP SQL创建树结构

时间:2017-12-31 02:53:26

标签: php mysql sql

我在mySQL中有一个像这样的数据库表,并希望使用当前值child创建树结果。

id          item_id         secondary_id
1           1               1
2           1               1
3           1               1
4           1               3
5           1               3
6           1               3
7           1               3
8           1               3
9           1               3
10          1               3
11          1               3
12          1               1
13          1               1
14          1               1
15          1               1
16          1               7
17          1               7
18          1               7
19          1               7
20          1               7

我想得到这样的最终结果:

$current_value = 18;

  • - >以id = 1
  • 为根
  • --->回复id = 2
  • --->回复id = 3
  • ----->回复id = 6
  • ----->回复id = 7
  • ------->回复id = 16
  • ------->回复id = 17
  • ------->回复id = 18< - 此目标$current_value
  • ------->回复id = 19
  • ------->回复id = 20
  • ----->回复id = 8
  • ----->回复id = 9
  • --->回复id = 12
  • --->回复id = 13

我使用此SQL查询,但只从目标获取结果当前目标,先前值和下一个值。

$query = "(
    SELECT *
    FROM (
        SELECT *
        FROM table_name
        WHERE id < $current_target
        ORDER BY id
        LIMIT 2
    ) AS comment

    ORDER BY comment.id ASC
)

UNION ALL

(
    SELECT *
    FROM (
        SELECT *
        FROM table_name
        WHERE id = $current_target
        ORDER BY id DESC
        LIMIT 2
    ) AS comment

    ORDER BY comment.id ASC
)

UNION ALL

(
    SELECT *
    FROM (
        SELECT *
        FROM table_name
        WHERE id > $current_target
        ORDER BY id
        LIMIT 2
    ) AS comment

    ORDER BY comment.id
)";

我希望将结果提升到Root。

0 个答案:

没有答案