【发布时间】:2021-06-07 19:37:58
【问题描述】:
用于留言板系统。有一般帖子,以及对这些帖子的直接回复。
SELECT * FROM msgs ORDER BY msg_id ASC, msg_replyto ASC
不会给我想要的结果,因为它列出了所有的一般帖子,然后是所有的回复。我不知道该怎么表达我的要求,所以我所能做的就是给你模型表和数据。
这是示例表结构和行:
msg_id | msg_text | msg_replyto
----------------------------------------------------------------
1 | This is a post ID #1 | NULL
2 | This is a post ID #2 | NULL
3 | This is a direct reply to post ID #1 | 1
4 | This is a post ID #4 | NULL
5 | This is a post ID #5 | NULL
6 | This is a direct reply to post ID #4 | 4
7 | This is a post ID #7 | NULL
8 | This is a direct reply to post ID #3, | 3
| which is a direct reply to post ID #1. |
我尝试返回行的正确顺序如下:
msg_id | msg_replyto
-----------------------
1 | NULL
3 | 1
8 | 3
2 | NULL
4 | NULL
6 | 4
5 | NULL
7 | NULL
其中,首先 msg_id 具有优先级 - 除非一行中的字段 msg_replyto 等于另一行的 msg_id,然后 msg_replyto 具有次要优先级。如果这没有意义,我很抱歉,我没有其他方法可以解释它。我试着搜索这个,但什至不知道如何措辞。
这是创建示例的实际 SQL。
CREATE TABLE IF NOT EXISTS `msgs` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`msg_text` varchar(200) NOT NULL,
`msg_replyto` int(11) DEFAULT NULL,
PRIMARY KEY (`msg_id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `msgs` (`msg_id`, `msg_text`, `msg_replyto`) VALUES
(1, 'This is a post ID #1', NULL),
(2, 'This is a post ID #2', NULL),
(3, 'This is a direct reply to post ID #1', 1),
(4, 'This is a post ID #4', NULL),
(5, 'This is a post ID #5', NULL),
(6, 'This is a direct reply to post ID #4', 4),
(7, 'This is a post ID #7 ', NULL),
(8, 'This is a direct reply to post ID #3, which is a direct reply to post ID #1', 3);
COMMIT;
【问题讨论】:
-
你的MySql是什么版本的?
-
MYSQL 版本 5.7.31。我还安装了 8 个(我在笔记本电脑上使用 WAMPServer 作为 localhost)
-
我为示例表和数据集添加了 SQL。除此之外,我看不出我是怎么不遵守的。
标签: mysql sql sql-order-by