如何按新日期排序,然后按日期排序?

时间:2015-10-24 13:45:31

标签: php mysql sql sorting sql-order-by

我在mysql数据库中有日期列。我需要按日期排序ASC,但是先显示尚未发生的日期,然后发生了女巫。怎么做那个sql语句?结果示例:

for date 25 October 2015
new by ASC:
2015-10-25
2015-10-27
2015-11-03
...
then old by DESC:
2015-10-24
2015-10-14
2015-09-10
...

ps我正在使用Yii2框架(但干净的php也会很好)。

2 个答案:

答案 0 :(得分:2)

鉴于此样本数据:

CREATE TABLE t
    (`date` date)
;

INSERT INTO t
    (`date`)
VALUES
    ('2015-10-25'),
    ('2015-10-27'),
    ('2015-11-03'),
    ('2015-10-24'),
    ('2015-10-14'),
    ('2015-09-10')
;

和这个查询:

SELECT
date
FROM
t
ORDER BY
date >= CURDATE() DESC
, ABS(DATEDIFF(date, CURDATE()));

您可以获得所需的输出:

|                        date |
|-----------------------------|
|   October, 25 2015 00:00:00 |
|   October, 27 2015 00:00:00 |
|  November, 03 2015 00:00:00 |
|   October, 24 2015 00:00:00 |
|   October, 14 2015 00:00:00 |
| September, 10 2015 00:00:00 |

答案 1 :(得分:0)

在检查了fancyPants解决方案之后我傻了。

但我希望展示我正在使用的那个

<强> async

  SELECT *
  FROM (
        SELECT t.*,
               (@rn := if(true, @rn + 1, 1)
               ) as rn
        FROM myTable t         
        CROSS JOIN
              (select @rn := 0) params
        WHERE dateField >= NOW()
        ORDER BY dateField asc
      ) X
  UNION 
  SELECT *
  FROM (
        SELECT t.*,
                 (@bn := if(true, @bn + 1, 1)
                 ) as rn
        FROM myTable t         
        CROSS JOIN
              (select @bn := (SELECT COUNT(*) 
                              FROM myTable 
                              WHERE dateField >= NOW()
                             ) a
              ) params
        WHERE dateField < NOW()
        ORDER BY dateField desc
      ) Y 

<强>输出

|                   dateField | rn |
|-----------------------------|----|
|   October, 25 2015 00:00:00 |  1 |
|   October, 27 2015 00:00:00 |  2 |
|  November, 03 2015 00:00:00 |  3 |
|   October, 24 2015 00:00:00 |  4 |
|   October, 14 2015 00:00:00 |  5 |
| September, 10 2015 00:00:00 |  6 |