2014-04-02 74 views
0

这是我的SQL查询PHP的Mysql按日期排序

CREATE TABLE IF NOT EXISTS `categories` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(255) NOT NULL DEFAULT '', 
    `revise_price_option` int(1) NOT NULL, 
    `sale_start_date` datetime NOT NULL, 
    `sale_end_date` datetime NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ; 
INSERT INTO `categories` (`id`, `name`, `revise_price_option`, `sale_start_date`, `sale_end_date`) VALUES 
(1, 'Subwoofers', 1, '2014-04-02 08:00:00', '2014-04-02 14:00:00'), 
(2, 'Speakers', 1, '2014-04-02 12:00:00', '2014-04-02 14:05:00'), 
(3, 'test', 1, '2014-04-03 10:00:00', '2014-04-04 12:00:00'), 
(4, 'Amplifiers', 1, '2014-04-02 10:30:00', '2014-04-02 14:05:00'), 
(5, 'atest1', 1, '2014-04-02 16:30:00', '2014-04-03 17:00:00'); 

在这里,我想用日期排序。 如果开始日期和结束日期小于当前日期,应该desc.Start和结束的最近日期应该是顶部和过期日期应低于

我的查询是:

SELECT * FROM categories WHERE revise_price_option='1' ORDER BY sale_start_date, sale_end_date 
+1

那么这有什么问题吗?你的实际结果是什么?预期的结果是什么? – Marcel

+0

过去的日期首先显示,我想超过当前日期应该是顶部和过去的日期应该是底部 – Prakash

回答

2

这是一个有点棘手,因为您不能使descasc部分条件。所以,首先放过期的。然后对它们进行排序递减,其余的上升:

SELECT * 
FROM categories 
WHERE revise_price_option='1' 
ORDER BY (sales_start_date < now() and sale_end_date < now()) desc, 
     (case when (sales_start_date < now() and sale_end_date < now()) 
       then sale_start_date 
      end) desc 
     sale_start_date asc; 
0

您可以使用PHP的if else执行哪个查询要使用。 示例结构:

if(start_date < current date){ 
    //execute query DESC 
    } 
    else{ 
    //execute query ASC 
    } 
0

如果我没有理解你,这应该做你想做的:

SELECT * FROM categories WHERE sale_start_date <= NOW() AND sale_end_date <= NOW() ORDER BY sale_start_date DESC, sale_end_date DESC 
0

这里是过期的日期将在下面和非到期日上市将列出最前一页代码或从顶部。

SELECT * 
FROM categories 
WHERE revise_price_option='1' 
ORDER BY 
(sale_start_date > now() and sale_end_date > now()) desc; 

这里是sqlfiddle

0

试试这个 -

SELECT * FROM categories 
WHERE revise_price_option=1 
ORDER BY sale_start_date, sale_end_date 
CASE WHEN (sale_start_date < NOW() AND sale_end_date < NOW()) THEN desc ELSE asc END