MySql - иерархия для вложенных комментариев - PullRequest
0 голосов
/ 25 сентября 2019

У меня есть таблица, которая содержит комментарии пользователей, определенные следующим образом:

CREATE TABLE UserComments (
    `ID` INT NOT NULL,
    `Content` TEXT,
    `Rank` TEXT,
    `Number`INT NOT NULL,
    `Parent` INT,
    PRIMARY KEY (`ID`),
    FOREIGN KEY (`Parent`) REFERENCES UserComments(`ID`)
);

INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`) VALUES ('1', '<p>First root comment</p>', '1', '1');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`) VALUES ('2', '<p>Second root comment</p>', '2', '2');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`) VALUES ('3', '<p>Third root comment</p>', '3', '3');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`, `Parent`) VALUES ('5', '<p>First reply to 3rd comment</p>', '3-5', '5', '3');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`, `Parent`) VALUES ('6', '<p>First reply to first reply of 3rd comment</p>', '3-5-6', '6', '5');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`, `Parent`) VALUES ('7', '<p>Second reply to 3rd comment</p>', '3-7', '7', '3');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`, `Parent`) VALUES ('8', '<p>Third reply to 3rd comment</p>', '3-8', '8', '3');
INSERT INTO `UserComments` (`ID`, `Content`, `Rank`, `Number`) VALUES ('4', '<p>Fourth root comment</p>', '4', '4');

Способ отображения иерархии для моей таблицы заключается в ранжировании моих комментариев по пути, показанному в этом примере

ID   Content                                     Rank     Parent
1   'First root comment',                        '1'      NULL
2   'Second root comment',                       '2'      NULL
3   'Third root comment',                        '3'      NULL
5   'First reply to 3rd comment',                '3-5'    '3'
6   'First reply to first reply of 3rd comment', '3-5-6'  '5'
7   'Second reply to 3rd comment',               '3-7'    '3'
8   'Third reply to 3rd comment',                '3-8'    '3'
4   'Fourth root comment',                       '4'      NULL

SELECT * FROM UserComments ORDER BY `Rank`

Как видите, это хорошо работает для комментариев, которые показывают от Старейший до Новейшего .Новейшие корневые комментарии всегда будут появляться в конце таблицы.Проблема возникает, когда я хочу сделать обратное, и упорядочить мои корневые комментарии от От самых новых до самых старых .При попытке сделать заказ в обратном порядке отображается следующее дерево.Порядок комментариев, конечно, неверен.Дети укладываются выше своих родителей

ID   Content                                     Rank     Parent
4   'Fourth root comment',                       '4'      NULL
8   'Third reply to 3rd comment',                '3-8'    '3'
7   'Second reply to 3rd comment',               '3-7'    '3'
6   'First reply to first reply of 3rd comment', '3-5-6'  '5'
5   'First reply to 3rd comment',                '3-5'    '3'
3   'Third root comment',                        '3'      NULL
2   'Second root comment',                       '2'      NULL
1   'First root comment',                        '1'      NULL
ID   Content                                     Rank     Parent
4   'Fourth root comment',                       '4'      NULL
3   'Third root comment',                        '3'      NULL // ORDERED CORRECTLY
5   'First reply to 3rd comment',                '3-5'    '3'
6   'First reply to first reply of 3rd comment', '3-5-6'  '5'
7   'Second reply to 3rd comment',               '3-7'    '3'
8   'Third reply to 3rd comment',                '3-8'    '3'
2   'Second root comment',                       '2'      NULL
1   'First root comment',                        '1'      NULL

Мой вопрос: как я могу решить эту проблему?Есть ли способ, которым я могу построить запрос, который позволит мне заказать его таким образом?Причина, по которой я хотел бы, чтобы он был упорядочен таким образом, заключается в том, что я могу реализовать разбиение на страницы через LIMIT.

Было бы проще сделать это на уровне приложения?

...