按日期和时间排序的SQL顺序不起作用

时间:2015-05-21 17:48:29

标签: php mysql sql

我正在尝试按时间和日期排序邮件,但它不起作用: 这是我的代码:

$sql="SELECT id, message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction
        FROM message
        WHERE
            (recipient = $friend_id OR sender = $friend_id)
            AND id > $last_message_id ORDER BY time AND date ASC";

3 个答案:

答案 0 :(得分:1)

您的语法略有偏差。多列的排序规范需要以逗号分隔。试试这个:

$sql="SELECT id, message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction
        FROM message
        WHERE
            (recipient = $friend_id OR sender = $friend_id)
            AND id > $last_message_id ORDER BY time ASC, date ASC";

作为旁注,ASC是默认的排序顺序,因此您无需明确指定它。

答案 1 :(得分:1)

它应该是ORDER BY time ASC, date ASC,假设两者都是适当的数据类型;如果它们是字符串类型,它并不总是按照需要运行。

答案 2 :(得分:1)

你需要将ASC与这两个栏目放在一起: -

$sql="SELECT id, message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction
        FROM message
        WHERE
            (recipient = $friend_id OR sender = $friend_id)
            AND id > $last_message_id ORDER BY time ASC, date ASC";