I am trying to sort data on two date fields, start and end. But there is a peculiar condition. It should sort on both the fields parallely.
My users table
id | start | end
---------------------------------------------------
1 | 2015-02-24 00:00:00 | 2015-02-18 00:00:00
---------------------------------------------------
2 | 2015-02-24 00:00:00 | 2015-02-03 00:00:00
---------------------------------------------------
3 | 2015-02-25 00:00:00 | NULL
---------------------------------------------------
4 | 2015-02-23 00:00:00 | NULL
---------------------------------------------------
Expected Output:
id | start | end
---------------------------------------------------
3 | 2015-02-25 00:00:00 | NULL
---------------------------------------------------
4 | 2015-02-23 00:00:00 | NULL
---------------------------------------------------
1 | 2015-02-24 00:00:00 | 2015-02-18 00:00:00
---------------------------------------------------
2 | 2015-02-24 00:00:00 | 2015-02-03 00:00:00
---------------------------------------------------
As you can see the row with id 1 comes in the 3rd place because the value of end date exists and it is smaller than the previous record start date.
The table should sort on both the fields at the same time. And it should give a higher priority to the end field. But if the end field is null, it should carry on the sorting on START field.
I have tried the below queries:
SELECT * FROM `users` order by end DESC, start DESC
SELECT * FROM `users` order by start DESC,least(start,end) DESC
The above queries gives me a result which is something like this but as you can see it didn't consider the end date. I mean it did, but thats not how i want:
id | start | end
---------------------------------------------------
3 | 2015-02-25 00:00:00 | NULL
---------------------------------------------------
1 | 2015-02-24 00:00:00 | 2015-02-18 00:00:00
---------------------------------------------------
2 | 2015-02-24 00:00:00 | 2015-02-03 00:00:00
---------------------------------------------------
4 | 2015-02-23 00:00:00 | NULL
---------------------------------------------------
Below is the create table and sample data if you want to execute and try.
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `start`, `end`) VALUES
(1, '2015-02-24 00:00:00', '2015-02-03 00:00:00'),
(2, '2015-02-24 00:00:00', '2015-02-18 00:00:00'),
(3, '2015-02-25 00:00:00', NULL),
(4, '2015-02-23 00:00:00', NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;