繁体   English   中英

PHP Mysql按日期排序

[英]PHP Mysql sorting by date

这是我的SQL查询

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');

在这里,我想按日期排序。 如果start_date和end_date小于当前日期,则应该desc.Start和end的最近日期应该是top,过期日期应该低于

我的疑问是:

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

这有点棘手,因为你无法使排序的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;

您可以使用php if else来执行您要使用的查询。 示例结构:

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

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

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

以下是代码,其中过期日期将在下面列出,非过期日期将列为fisrt或从顶部。

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

这是sqlfiddle

尝试这个 -

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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