用于消息回复系统的MySQL高级ORDER BY子句

时间:2013-08-08 12:18:04

标签: mysql sql select sql-order-by

我有一个用户可以发帖子的页面。对于发布的每条消息,有人可以在原始消息之后立即显示回复。

请参阅我的MySQL表:

id | user_id  | message                    | date                | second_reply_id
1    48         Hi i post a message          2013-08-08 13:00:00   0
2    20         Hi i also post a message     2013-08-08 14:00:00   0
3    17         And i reply to message 1     2013-08-08 15:00:00   1
4    8          And i reply to message 2     2013-08-08 16:00:00   2
5    10         Hi i post a new message      2013-08-08 17:00:00   0
6    7          i reply to reply id 3        2013-08-08 18:00:00   1

有没有办法按如下顺序排序选择查询的结果:

id | user_id  | message                    | date                | second_reply_id 
5    10         Hi i post a new message      2013-08-08 17:00:00   0
2    20         Hi i also post a message     2013-08-08 14:00:00   0
4    8          And i reply to message 2     2013-08-08 16:00:00   2
1    48         Hi i post a message          2013-08-08 13:00:00   0
3    17         And i reply to message 1     2013-08-08 15:00:00   1  
6    7          i reply to reply id 3        2013-08-08 18:00:00   1 

谢谢

2 个答案:

答案 0 :(得分:4)

试试这个(不幸的是,如果您可以回复回复,这将不起作用):

SELECT
    id ,
    user_id,
    message,
    date,
    second_reply_id
FROM 
    my_table 
ORDER BY
    second_reply_id,
    IF(
        second_reply_id = 0,
        id,
        second_reply_id
    )

更新:订购从最旧到最新的回复只需使用:

ORDER BY IF(second_offer_id =0, id, second_offer_id ) ASC , IF(second_offer_id =0, 'xxxx', date ) DESC

答案 1 :(得分:1)

通过reply_to_id和日期

将表格加入自己的广告订单