【问题标题】:How to sort two different date columns in mysql in descending order?如何按降序对mysql中的两个不同日期列进行排序?
【发布时间】:2013-08-01 01:24:01
【问题描述】:

谁能帮助我如何在 mysql 中对两个不同的日期列进行排序?

我使用具有两个不同列的表创建了一个查询。第一个是 cert_date,另一个是 special_training_date_from。我想要做的是当我执行查询时,输出必须是这样的: cert_date 和 special_training_date_from 列必须按降序排序。例如,如果 cert_date 是 '2012-01-03, 2012-07-07' 而 special_training_date_from 是 '2011-05-03, 2013-08-01',那么输出必须是:

2013-08-01, 2012-07-07, 2012-01-03, 2011-05-03

这是我使用的查询。

Select training_title, cert_date, special_training_date_from 
from tabletraining 
order by cert_date + sptrain_from desc;

每次我按升序排序结果都是正确的,但我想按降序排序,每次我输入'desc'关键字时,结果都会不正确。

【问题讨论】:

  • 我有点困惑。您能否发布一些示例数据和您期望的完整输出?

标签: mysql


【解决方案1】:

您可以将日期放在单个列中以使用order by

select training_title, thedate, which
from ((Select training_title, cert_date as thedate, 'cert' as which
       from tabletraining
      ) union all
      (select training_title, special_training_date_from, 'special' as which
       from tabletraining
      )
     ) t
order by thedate desc;

编辑:

如果您只想要两列中的不同日期,请使用:

select distinct thedate
from ((Select training_title, cert_date as thedate, 'cert' as which
       from tabletraining
      ) union all
      (select training_title, special_training_date_from, 'special' as which
       from tabletraining
      )
     ) t
order by thedate desc;

【讨论】:

  • @Jessa 。 . .不,我只是添加它来说明数据的来源。没有必要获取日期。这里的用途是作为列别名。
  • 先生,我对“证书”和“特殊”这两个词感到困惑。
  • 先生,我已经尝试过您的建议,但结果是重复的行。
【解决方案2】:

试试这个...

order by CONCAT(cert_date,sptrain_from) desc;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多