【发布时间】:2016-09-30 05:49:30
【问题描述】:
我正在使用 MySQL,是否可以从下面的表结构中获取单个 SQL 语句的以下结果?
目前我可以通过在我的 PHP 代码中使用 逻辑 while 循环来获得相同的结果。如果我能在单个 SQL 中实现,那就更好了。
预期结果:
|----------+-----------------------------------------------+
| Id (PK) + headerANDsubheader +
|----------+-----------------------------------------------+
| 1 + A-head +
| 4 + -A-head-A1-subHead +
| 5 + -A-head-A2-subHead +
| 6 + --A-head-A1-subHead-A1.1-subHead +
| 7 + --A-head-A1-subHead-A1.2-subHead +
Id 列是主键。如果父键为 0,则表示其根级标题。
如果ParentKey 不等于0,则表示它是某人的子标题,ParentKey 是指向它的指针。
表:Header_sub
|----------+-----------------------------------------------+------------+
| Id (PK) + headerANDsubheader + ParentKey +
|----------+-----------------------------------------------+------------+
| 1 + A-head + 0 +
|----------+-----------------------------------------------+------------+
| 2 + B-head + 0 +
|----------+-----------------------------------------------+------------+
| 3 + C-head + 0 +
|----------+-----------------------------------------------+------------+
| 4 + A-head-A1-subHead + 1 +
|----------+-----------------------------------------------+------------+
| 5 + A-head-A2-subHead + 1 +
|----------+-----------------------------------------------+------------+
| 6 + A-head-A1-subHead-A1.1-subHead + 4 +
|----------+-----------------------------------------------+------------+
| 7 + A-head-A1-subHead-A1.2-subHead + 4 +
|----------+-----------------------------------------------+------------+
我正在尝试这样......
SELECT
CONCAT(REPEAT(' ', (COUNT(parent.subject_group_name) - 1) ), node.subject_group_name) AS name
FROM
major_scholastic as node,
major_scholastic as parent
WHERE
node.s_gid BETWEEN parent.s_gid AND parent.parent_id
GROUP BY node.subject_group_name
ORDER BY node.s_gid
【问题讨论】:
-
为什么查询和示例数据中的表名和列名不匹配?
-
如果 header_sub 是您的实际表结构:为什么不在更新路径时将深度添加为列并在
repeat中使用它?
标签: mysql