MySql中的分层数据
我有一个与父子关系的表,我需要递归查询的帮助
roleId, roleName, parentId1 Admin 0
2 Backup Admin 1
3 Office User 1 0
4 User 1 3
5 User 2 3
6 Office User 2 0
7 Off User 1 6
我正在尝试进行递归查询,但是我无法做到这一点,建议我应该如何查询数据库
Admin -- Backup Admin
Office User 1
-- User 1
-- User 2
Office User 2
-- Off User 1
回答:
正如上面所指出的,这并不是真正的递归,但是如果您知道最大需要深入多少步,则可以沿以下方向使用某些方法(也许使用PHP生成查询):
我首先将父ID设置为NULL而不是0,但这是个人喜好。
SELECT * FROM table t1LEFT JOIN table t2 ON t2.parent_id = t1.role_id
LEFT JOIN table t3 ON t3.parent_id = t2.role_id
WHERE t1.parent_id IS NULL
^^在这种情况下,您需要走多远。
[ ]
然后,您可以按照以下方式操作输出:
SELECT (CASE
WHEN (t1.name IS NULL AND t2.name IS NULL) THEN t3.name
WHEN (t1.name IS NULL AND t2.name IS NOT NULL) THEN t2.name
ELSE t1.name END) AS first,
(CASE
WHEN (t1.name IS NOT NULL AND t2.name IS NOT NULL) THEN t2.name
WHEN (t2.name IS NULL AND t3.name IS NOT NULL) THEN NULL
ELSE t3.name END) AS second,
(CASE
WHEN (t1.name IS NOT NULL) THEN t3.name
ELSE NULL END) AS third
FROM
以上是 MySql中的分层数据 的全部内容, 来源链接: utcz.com/qa/399463.html