日期和月份未知的值的订购日期

order date for values with unknown day and month

我正在开发一个包含过去事件的网站。对于某些事件,整个日期是已知的,对于某些事件,是一年中的月份,而对于某些事件,则仅知道年份。 Table 事件看起来像:

id
content
date -> YYYY-MM-DD (date data type)
year -> true, if only year is known, otherwise false
monthandyear -> true if only year and month is known, otherwise false

我想按以下顺序列出table的内容:

这个问题的最佳解决方案是什么?

我正在使用 DQL:

SELECT p FROM App:Event p ORDER BY p.date DESC ...

您可以使用条件逻辑。假设 date 是一个字符串:

order by left(date, 4),
         (case when not year and not yearmonth then 1 else 2 end),
         left(date, 7),
         (case when not yearmonth then 1  else 2 end)
         date

编辑:

如果datedate类型,那么:

order by year(date),
         (case when not year and not yearmonth then 1 else 2 end),
         month(date),
         (case when not yearmonth then 1  else 2 end)
         date

我使用 Gordon 的回答解决了这个问题。在 DQL 中它看起来像:

$this->getEntityManager()
     ->createQuery(
            'SELECT '
                . 'p, '
                . '(CASE WHEN (p.year = :yes) THEN 1 ELSE 2 END) as HIDDEN ORD1, '
                . '(CASE WHEN (p.monthandyear = :yes) THEN 1 ELSE 2 END) as HIDDEN ORD2 '
                . 'FROM App:Event p '
                . 'ORDER BY SUBSTRING(p.dateandtime, 1, 4) DESC, ORD1 DESC, SUBSTRING(p.dateandtime, 1, 7) DESC, ORD2 DESC, p.dateandtime DESC'  
        )
        ->setParameters(array("no" => false, "yes" => true))
        ->getResult();