【问题标题】:Using IS NULL and COALESCE in OrderBy Doctrine Querybuilder在 OrderBy Doctrine Querybuilder 中使用 IS NULL 和 COALESCE
【发布时间】:2013-08-11 12:16:20
【问题描述】:

我基本上有以下(My)SQL-Query

SELECT * FROM `address`
ORDER BY ISNULL(`company`), `company` ASC, COALESCE(`parent_id`, `address_id`), `parent_id` IS NOT NULL

哪个做得好

我的目标是以下排序输出

ID| PARENT_ID | COMPANY | NAME
1 | NULL      | A       | NULL
2 | 1         | A.A     | NULL
3 | 1         | A.B     | NULL
4 | NULL      | B       | NULL
5 | NULL      | C       | NULL
6 | NULL      | D       | NULL
7 | 6         | D.A     | NULL
8 | NULL      | NULL    | A

我正在使用 Symfony 2 和 Doctrine。 目前我使用 Doctrine 查询生成器,因为 OrderBy 应该是我用不同方面实现的搜索的一部分(按标签搜索,按不同字段“地址”搜索...)

当我尝试将“IS NULL”或“COALESCE”添加到

$qb->add('orderBy', ' >ORDERBY_STATEMENT< ');

或以任何其他方式使用查询生成器编写 order by 语句

我得到以下信息

[Syntax Error] line 0, col 90: Error: Expected end of string, got 'IS'

我发现 Doctrine 不是特定于供应商的,因此不能支持所有供应商功能。

我阅读了一篇关于扩展 Doctrines DQL 函数的文章。但是已经有一个使用 Doctrine Expressions 的“isNull”函数在我的 OrderBy 中不起作用。

有人知道我如何使用查询构建器来实现所描述的 OrderBy 语句吗?

【问题讨论】:

  • 如果你改用$qb-&gt;add('orderBy', 'company IS NULL');会怎样?
  • 似乎只能按一个方向按一列排序(无论如何都有意义-_-)当然我用你的代码测试了它,但是我又错过了它的 COALESCE 部分
  • 感谢更新,我设法用我自己的扩展来解决当前的问题

标签: mysql symfony doctrine-orm doctrine sql-order-by


【解决方案1】:

谢谢Andi Sholihin

我只是在 symfony 3 下发布了一个带有 IDENTITY() 函数的可行替代方案:)

$repository = $this->getDoctrine()->getRepository(Address::class);
$query = $repository->createQueryBuilder('a')
    ->select('a, COALESCE(IDENTITY(a.parent), a.id) as columnOrder')
    ->orderBy('columnOrder', 'ASC')
    ->addOrderBy('a.parent', 'ASC')
    ->getQuery();

【讨论】:

    【解决方案2】:

    也许这会有所帮助:

    $qb = $em->createQueryBuilder();
    $qb->select('Entity, COALESCE(Entity.column1, Entity.column2) as columnOrder')
       ->from('Namespace\EntityName', 'Entity')
       ->addOrderBy('columnOrder', 'ASC')
       ->getQuery()
       ->execute();
    

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 2012-05-22
      相关资源
      最近更新 更多