doushuzd3033 2014-08-25 11:04
浏览 146
已采纳

Mysql:将最新评论排序为每个评论的最新和最新回复

I have a table with hierarchical-data (comments with replies) and I wonder how I can sort it so that the newest comments will be prepended as the first ones and the newest replies for each comment should be appended as the last ones.

An example of the table

Here is an example of what it looks like:

id   |   path    |   reply_to   |   date
1         1            NULL         8:00
2        1-2            1           9:00
3        1-3            1          10:00
4         4            NULL        11:00
5        1-5            1          12:00
6        4-6            4          13:00
7        4-7            4          14:00

If I want to select the path of my result, it should be ordered like this:

4
4-6
4-7
1
1-2
1-3
1-5

Is this possible using MySQL queries?

What I have been doing until now

Until now, I have only selected the rows with no replies ordered by ID DESC, and then (for each row) I requested its replies and ordered them by ID ASC, I used PDO in PHP to connect to my database:

$stmt1 = $this->db->query("SELECT * FROM comments WHERE reply_to IS NULL ORDER BY id DESC");
$stmt2 = $this->db->prepare("SELECT * FROM comments WHERE reply_to = ? ORDER BY id ASC");
while($row = $stmt1->fetch()) {
    //display the comment
    $stmt2->execute(array($row['id']));
    while($row2 = $stmt2->fetch()) {
        //display all its replies
    }
}

But I think if I query only one time it would be much better than querying inside of a loop like I am doing now, right?

I hope my question is understandable. Unfortunately, I have no idea how to solve this problem. I thought that SQL Joins are the solution, but as far as I know they are "used to combine rows from two or more tables, based on a common field between them".

Here is an SQL Fiddle to play around.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • duanpo7354 2014-08-25 11:13
    关注

    This is a bit complicated, but you can do it (at least for the data shown in the question). The idea is to bring in the parent information ("reply to"). Then sort by the following:

    • Parent's date and parent's id -- so all parent messages are together
    • Then put the parent first
    • Then order the rest by the time

    This is the query:

    select c.*
    from comments c left join
         comments cparent
         on c.reply_to = cparent.id
    order by coalesce(cparent.date, c.date) desc,
             coalesce(cparent.id, c.id),
             (cparent.id is null) desc,
             c.date asc;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决,来真人,不要ai!
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法