Home  >  Q&A  >  body text

Mysql date sorting error

SELECT
co.id,
IFNULL( oe.follow_status, 'unFollow' ) AS followStatus,
co.due_time 
FROM
car_order co
LEFT JOIN order_expire oe ON oe.order_id = co.id 
WHERE
co.type = '贷款' 
AND co.STATUS = '已放款' 
AND co.approve_status != '结清成功' 
AND date_FORMAT( co.due_time, '%Y-%m-%d' ) <= '2022-10-29' 
ORDER BY
field( oe.follow_status, 'unFollow', 'follow' ),
co.due_time DESC,
co.id DESC

Date sorting error. How should I write it?

P粉759451255P粉759451255178 days ago336

reply all(2)I'll reply

  • P粉440453689

    P粉4404536892024-04-05 11:17:25

    SELECT
    co.id,
    IFNULL( oe.follow_status, 'unFollow' ) AS followStatus,
    co.due_time 
    FROM
    car_order co
    LEFT JOIN order_expire oe ON oe.order_id = co.id 
    WHERE
    co.type = '贷款' 
    AND co.STATUS = '已放款' 
    AND co.approve_status != '结清成功' 
    AND co.due_time <= '2022-10-29' 
    ORDER BY
    field( followStatus, 'unFollow', 'follow' ),
    co.due_time DESC,
    co.id DESC

    You should sort by the IFNULL alias followStatus instead.

    reply
    0
  • P粉064448449

    P粉0644484492024-04-05 00:21:23

    Assuming due_time is a timestamp column, you should be able to compare it directly to a date literal:

    SELECT co.id,
           IFNULL(oe.follow_status, 'unFollow') AS followStatus,
           co.due_time 
    FROM car_order co
    LEFT JOIN order_expire oe ON oe.order_id = co.id 
    WHERE co.type = '贷款' AND 
          co.STATUS = '已放款' AND
          co.approve_status != '结清成功' AND
          co.due_time <= '2022-10-29' 
    ORDER BY FIELD(oe.follow_status, 'unFollow', 'follow'),
             co.due_time DESC,
             co.id DESC;
    

    DATE_FORMAT() The function is used to convert date/timestamp to string, but it is not needed here as date/timestamp columns can be compared directly.

    reply
    0
  • Cancelreply