Mysql让爷爷孙子一路下来

标签 mysql

+-----------+-----------------+
| AccountID | ParentAccountID |
+-----------+-----------------+
|         1 |            NULL |
|         2 |               1 |
|         3 |               2 |
|         5 |               3 |
|         6 |               5 |
|         7 |               6 |
|         8 |               7 |
|         9 |               8 |
|        10 |               9 |
|        11 |              10 |
|        12 |              11 |
|        13 |              12 |
|        14 |              13 |
|        15 |              14 |
|        16 |              15 |
|        17 |              16 |
|        18 |              17 |
|        19 |              18 |
|        20 |              19 |
+-----------+-----------------+

我正在寻找一个简单的查询来根据父帐户 ID 列出所有子项和孙项。

例如 AccountID (1) 的子代和孙代为 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 ,20 AccountID(14) 的子代和孙代为 15,16,17,18,19,20

我尝试了很多查询,只返回上一级。请帮忙解决这个问题。提前致谢

最佳答案

您想要整个层次结构,而不仅仅是两个级别。因此,为此您必须在表中添加另一列。

+-----------+-----------------++-----------------+
| AccountID | ParentAccountID | Hierarchy        |
+-----------+-----------------+------------------+
|         1 |            NULL |                  | 
|         2 |               1 |-1->              |
|         3 |               2 |-1->-2->          |
|         5 |               3 |-1->-2->-3->      |
|         6 |               5 |-1->-2->-3->-5->  |
+-----------+-----------------+-+----------------+ etc.

我只是给出如何构建结构的提示。

DELIMITER $$

CREATE PROCEDURE build_hierarchy ()
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
 Declare var_AccountId integer;
 Declare var_ParentAccountID integer;
 Declare var_Hierarchy integer;
 Declare cur_all_accounts cursor for select * from accounts;
-- declare NOT FOUND handler
 DECLARE CONTINUE HANDLER 
        FOR NOT FOUND SET v_finished = 1;
get_data: LOOP

 FETCH cur_all_accounts INTO var_AccountId, var_ParentAccountID,var_Hierarchy ;

 IF v_finished = 1 THEN 
 LEAVE get_data;
 END IF;

Update Accounts set hierarchy = (select Hierarchy + '-' + accountId + '->' from Accounts 
where accountId = var_ParentaccountId) where AccountID = var_accountId;

 END LOOP get_data;

 CLOSE cur_all_accounts;

END$$

DELIMITER ;

然后运行该过程。

CALL build_hierarchy();

要获取 ParentAccountId = 1 的层次结构,请运行以下查询。

select AccountID from Accounts where Hierarchy like = '%-' + parentAccountId+'->%';

关于Mysql让爷爷孙子一路下来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498322/

相关文章:

python - Django级联删除反向外键

MySQL LIKE 模式匹配在应该返回值时返回空集

php - 抑制或管理 cakephp 中的 "duplicate-entry"错误

java - Spring @Transactional 不回滚

android - AsyncTask、doinBackground 永远不会完成

mysql - 与同一实体的记录的数据库关联关系

mysql - swi prolog mysql + web

PHP多数据库连接

php - 折线图上的 Google Chart API 无效 JSON 字符串

javascript - 将 MySQL 数据库表值导出到 HTML 文件