I am implementing pagination of a tree structure table in mysql. I have a Table: account with recursive association, an account can be boss of other account. A self relationship of kind (SuperVisor (1)- SuperVisee (∞) ).
Query to Create Table:
CREATE TABLE account (
AccountId char(36) NOT NULL DEFAULT '' COMMENT 'key',
AccountParentId char(36) DEFAULT NULL COMMENT 'Id root node',
CreatedDate datetime DEFAULT NULL COMMENT 'created date',
PRIMARY KEY (AccountId)
)
ALTER TABLE account
ADD CONSTRAINT FK_account_AccountParentId FOREIGN KEY (AccountParentId)
REFERENCES account (AccountId);
I have inserted a set of tuples (Query):
INSERT INTO account VALUES
("1", "null", "2001-01-02"),
("2", "1", "2001-02-02"),
("3", "2", "2001-03-02"),
("4", "null", "2001-04-02"),
("5", "4", "2001-05-02"),
("6", "null", "2001-06-02"),
The inserted rows has the following Tree-Hierarchical-Relationship:
- 1
- 2
- 3
- 4
- 5
- 6
I wrote a procedure to perform paging of account table data:
PROCEDURE Proc_Account_Pagination(IN p_PageNumber INT, IN p_PageSize INT)
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS tbAccountOrginal AS
WITH RECURSIVE AccountTree AS
(
SELECT AccountId, AccountParentId, CAST(CreatedDate AS CHAR(200)) AS CreatedDate, CAST(AccountId AS CHAR(200)) AS path,
0 AS depth FROM view_account WHERE AccountParentId IS NULL
UNION ALL
SELECT
va.AccountId,
va.AccountParentId,
AccountTree.CreatedDate,
CONCAT(AccountTree.path, ",", va.AccountId),
AccountTree.depth+1 FROM view_account va JOIN AccountTree ON AccountTree.AccountId=va.AccountParentId
)
SELECT ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) AS RowIndex,
AccountId,
AccountParentId,
path,
depth FROM AccountTree ORDER BY path;
SELECT * FROM tbAccountOrginal eo WHERE eo.RowIndex BETWEEN @IndexStart AND @IndexEnd;
DROP TEMPORARY TABLE IF EXISTS tbAccountOrginal;
END
For example, I want when I select the number of records on 1 page is 3, the data displayed is 3 parent accounts and the child accounts of those 3 parent accounts. Child accounts are displayed under its parent account, the output of the above procedure is:
AccountId | AccountParentId | Path | Depth |
---|---|---|---|
1 | null | 1 | 0 |
2 | 1 | 1, 2 | 1 |
3 | 2 | 1, 2, 3 | 2 |
But I want to receive such a structure:
AccountId | AccountParentId | Path | Depth |
---|---|---|---|
1 | null | 1 | 0 |
2 | 1 | 1, 2 | 1 |
3 | 2 | 1, 2, 3 | 2 |
4 | null | 4 | 0 |
5 | 4 | 4, 5 | 1 |
6 | null | 6 | 0 |
I have tried adding WHERE AccountParentId IS NULL
to the query to the AccountTree recursive table but the result shows up like this:
AccountId | AccountParentId | Path | Depth |
---|---|---|---|
1 | null | 1 | 0 |
4 | null | 4 | 0 |
6 | null | 6 | 0 |
I really hope everyone can help me. Thanks a lot.