我正在开发 Symfony 3.4 项目。
如果存在(不为空),我想按 updated_at
排序表,如果不存在,则按 created_at
排序。
在 SQL 中,这有效:
SELECT * FROM `contract`
ORDER BY
(CASE WHEN ISNULL(`updated_at`) THEN `created_at` ELSE `updated_at` END)
DESC
我尝试了很多方法,但未能使其与 Doctrine Query Builder 一起使用。
首先,我尝试了这个(语法错误):
$contracts = $em->createQuery(
'SELECT c
FROM AppBundle:Contract c
ORDER BY (CASE WHEN c.updatedAt = :update THEN c.createdAt ELSE c.updatedAt END) DESC')
->setParameter('update', NULL)
->getResult();
然后,我按照this topic尝试了这个,但我没有结果(没有错误):
$contracts = $rp->createQueryBuilder('c')
->select('(CASE WHEN c.updatedAt != :update THEN 1 ELSE 0 END) AS HIDDEN orderDate')
->orderBy('orderDate', 'DESC')
->addOrderBy('c.createdAt', 'DESC')
->setParameter('update', NULL)
->getQuery()->getResult();
如何按更新日期(如果已更新)对契约(Contract)进行排序,或如何按创建日期(如果未修改)对契约(Contract)进行排序?
如果有帮助,我使用 DoctrineExtensions bundle对于其他查询,我看到了 IfNull
和 IfElse
类,但我不知道如何在我的案例中使用它们。
最佳答案
经过多次尝试,终于找到了解决办法。
使用COALESCE
:返回列表中第一个不为空的值,因此如果A为空且B不为空,则COALESCE(A,B)
将返回B .
$contracts = $rp->createQueryBuilder('c')
->select('c')
->addSelect('COALESCE(c.updatedAt,c.createdAt) AS HIDDEN orderDate')
->orderBy('orderDate', 'DESC')
->getQuery()->getResult();
无需使用 DoctrineExtensions bundle 。
关于mysql - Symfony3-学说 : Order by Case When,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53497755/