SQL ORDER BY date problem

后端 未结 10 1434
情歌与酒
情歌与酒 2020-11-30 05:14

Can you please help me in solving this problem. I am trying to order the results of an SQL query by date, but I\'m not getting the results I need.

The query I\'m usi

相关标签:
10条回答
  • 2020-11-30 05:50

    This may help you in mysql, php.

    //your date in any format
    $date = $this->input->post('txtCouponExpiry');
    
    $day = (int)substr($date, 3, 2);
    $month = (int)substr($date, 0, 2);
    $year = (int)substr($date, 7, 4);
    
    $unixTimestamp = mktime(0, 0, 0, $year, $day, $month);
    
    // insert it into database
    'date'->$unixTimestamp;
    
    //query for selecting  order by date ASC or DESC
    select * from table order_by date asc;
    
    0 讨论(0)
  • 2020-11-30 05:54

    Try using this this work for me

    select *  from `table_name` ORDER BY STR_TO_DATE(start_date,"%d-%m-%Y") ASC
    

    where start_date is the field name

    0 讨论(0)
  • 2020-11-30 05:55

    It sounds to me like your column isn't a date column but a text column (varchar/nvarchar etc). You should store it in the database as a date, not a string.

    If you have to store it as a string for some reason, store it in a sortable format e.g. yyyy/MM/dd.

    As najmeddine shows, you could convert the column on every access, but I would try very hard not to do that. It will make the database do a lot more work - it won't be able to keep appropriate indexes etc. Whenever possible, store the data in a type appropriate to the data itself.

    0 讨论(0)
  • 2020-11-30 05:58

    I wanted to edit several events in descendant chonologic order, and I just made a :

    select 
    TO_CHAR(startdate,'YYYYMMDD') dateorder,
    TO_CHAR(startdate,'DD/MM/YYYY') startdate,
    ...
    from ...
    ...
    order by dateorder desc
    

    and it works for me. But surely not adapted for every case... Just hope it'll help someone !

    0 讨论(0)
  • 2020-11-30 06:02

    Unsure what dbms you're using however I'd do it this way in Microsoft SQL:

    select      [date]
    from        tbemp 
    order by    cast([date] as datetime) asc
    
    0 讨论(0)
  • 2020-11-30 06:03

    It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:

    select date
    from tbemp
    order by convert(datetime, date, 103) ASC
    

    style 103 = dd/MM/yyyy (msdn)

    0 讨论(0)
提交回复
热议问题