MySql-嵌套注释的层次结构排序

时间:2019-09-25 05:03:54

标签: mysql database tree relational-database hierarchy

我有一个包含用户注释的表,定义如下:

@media(max-width: 600px) {
  body {
    background: red; // this works
  }

  $marq-width: 100vw; // this will not work
  .marquee{width:$marq-width;}  // this works

}

此表显示层次结构的方式是通过用路径对我的注释进行排名,如本例所示

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

我的问题是,如何解决此问题?有什么方法可以构造一个查询,让我以这种方式进行排序?我想以这种方式订购它的原因是,这样我就可以通过LIMIT实现分页。

在应用程序级别上这样做会更容易吗?

0 个答案:

没有答案