简体   繁体   中英

how to order two date columns and get latest 20 records from one table in mariadb?

i have one table named as post in mariadb which contain columns

|| p_creation_dateAndTime || p_modification_dateAndTime ||

and both values are type of datetime

now i want 5 records from a table which is created or modified in order to descending order

which means now Current time is 10-10-2010 10:10:10 and entry in a table is like

p_creation_dateAndTime || p_modification_dateAndTime
07-07-2007 07-07-07    || NULL
02-02-2002 02-02-02    || NULL
03-03-2003 03-03-03    || 07-07-2007 07-07-07    
05-05-2005 05-05-05    || NULL
02-02-2002 02-02-02    || 09-09-2009 09-09-09
08-08-2008 08-08-08    || NULL

and i want the result to be like

p_creation_dateAndTime || p_modification_dateAndTime
02-02-2002 02-02-02    || 09-09-2009 09-09-09
08-08-2008 08-08-08    || NULL
07-07-2007 07-07-07    || NULL
03-03-2003 03-03-03    || 07-07-2007 07-07-07   
05-05-2005 05-05-05    || NULL
02-02-2002 02-02-02    || NULL 

like 09 > 08 > 07 > 07 > 05 > 02

any solution for this ?

the above code is used in my project which is same as stackoverflow site and when display question to users at that time this sorting is needed

thanks in advance

In MySQL or MariaDB or Postgres or Oracle or Teradata or DB2 or BigQuery or RedShift (and so on), use greatest() :

order by greatest(p_creation_dateAndTime,
                  coalesce(p_modification_dateAndTime, p_creation_dateAndTime)
                 ) desc,
         p_creation_dateAndTime desc -- in the event of ties

The coalesce() is to handle NULL values. If any argument to greatest() is NULL , then the returned value is NULL .

If you are indeed using the datetime data type, you do not have to worry about the format of the displayed date; the order by is based on the internal format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM