Sorting by date & time in descending order?

后端 未结 8 703
生来不讨喜
生来不讨喜 2020-11-28 10:57

all I want to display last 5 entered data for specific id. My sql query is,

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
          


        
相关标签:
8条回答
  • 2020-11-28 11:22
    SELECT * FROM (
                   SELECT id, name, form_id, DATE(updated_at) as date
                   FROM wp_frm_items
                   WHERE user_id = 11 && form_id=9
                   ORDER BY updated_at DESC
                 ) AS TEMP
        ORDER BY DATE(updated_at) DESC, name DESC
    

    Give it a try.

    0 讨论(0)
  • 2020-11-28 11:23

    putting the UNIX_TIMESTAMP will do the trick.

    SELECT id, NAME, form_id, UNIX_TIMESTAMP(updated_at) AS DATE
        FROM wp_frm_items
        WHERE user_id = 11 && form_id=9
        ORDER BY DATE DESC
    
    0 讨论(0)
  • 2020-11-28 11:24

    If you want the last 5 rows, ordered in ascending order, you need a subquery:

    SELECT *
    FROM
        ( SELECT id, name, form_id, DATE(updated_at) AS updated_date, updated_at
          FROM wp_frm_items
          WHERE user_id = 11 
            AND form_id=9
          ORDER BY updated_at DESC
          LIMIT 5
        ) AS tmp
    ORDER BY updated_at
    

    After reading the question for 10th time, this may be (just maybe) what you want. Order by Date descending and then order by time (on same date) ascending:

    SELECT id, name, form_id, DATE(updated_at) AS updated_date
    FROM wp_frm_items
    WHERE user_id = 11 
      AND form_id=9
    ORDER BY DATE(updated_at) DESC
           , updated_at ASC
    
    0 讨论(0)
  • 2020-11-28 11:36

    If you mean you want to sort by date first then by names

    SELECT id, name, form_id, DATE(updated_at) as date
      FROM wp_frm_items
      WHERE user_id = 11 && form_id=9
      ORDER BY updated_at DESC,name ASC
    

    This will sort the records by date first, then by names

    0 讨论(0)
  • 2020-11-28 11:39

    I used a simpler solution found partly here:
    How to sort details with Date and time in sql server ?
    I used this query to get my results:

    SELECT TOP (5) * FROM My_Table_Name WHERE id=WhateverValueINeed ORDER BY DateTimeColumnName DESC

    This is more straight forward and worked for me.

    Notice: the column of the Date has the "datetime" type

    0 讨论(0)
  • 2020-11-28 11:42

    This is one of the simplest ways to sort record by Date:

    SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
    FROM article
    ORDER BY DATE DESC 
    
    0 讨论(0)
提交回复
热议问题