I have a mysql table which has values and dates, this is what I'm trying to accomplish in the mysql query: sort value DESC, (value>0 ? date asc : date desc) It will sort all values descending, then the equal values will be sorted by date ascending/descending depending if their value is zero or not I tried a lots of combinations, but failed miserably
I'd do something like this: https://www.db-fiddle.com/f/iTS44uh6ehu37a2cQv6bmH/0 create table `testing` ( id int(11) AUTO_INCREMENT, start_date DATE, primary key (id) )ENGINE=INNODB; insert into testing values (null, '2018-11-25'), (null,'2018-12-25'), (null, '2019-01-25'); select id, start_date, abs(datediff(now(), start_date)) as sortorder from `testing` order by sortorder Code (markup): The select creates a new column called "sortorder" and holds the number of days between now and the date of the record - and then gets the absolute (ie not a negative) number which makes the order by really easy.
I don't think you can do this directly by a query... However, first get the results by a simply query, then skip the "0" values in display... Your basic mysql query will look like this: $result= execQuery("select * from table order by value desc, date desc "); in php code, foreach( $result as $item ){ if( $item["date"] != 0 ){ // do the display } }//foreach By the way that execQuery() is a self written function, which sends query to database, and reads output in an array.