【问题标题】:Doctrine 查询语言每组的最新行
【发布时间】:2021-12-06 01:52:55
【问题描述】:

我正在尝试(但失败)将此 SQL 语句转换为使用 Doctrine QB。我正在尝试从“订单”表中获取每个客户的所有最新订单记录。

SELECT t1.* FROM order t1
  JOIN (SELECT id, MAX(timestamp) timestamp FROM order GROUP BY customer) t2
    ON t1.timestamp = t2.timestamp;

我已经尝试了几乎所有在这里找到的相关解决方案,我得到的最接近的是

$qb->join('App\Entity\Order', 'b', 'WITH', 'ro.date> b.date')

然而,它似乎适用于前 2 个结果,下面的结果似乎抓住了任何东西。请注意,我使用的是查询生成器,因为我有很多条件语句要添加“andWhere”和“orWhere”等。

【问题讨论】:

    标签: php mysql symfony doctrine greatest-n-per-group


    【解决方案1】:

    这应该会得到你想要的结果

    public function selectLastOrdersPerCustomer(){
        return $this->createQueryBuilder('o')
            ->leftJoin(Order::class, 'o2', 'WITH', 'o2.customer = o.customer AND o.timestamp < o2.timestamp')
            ->where( 'o2.timestamp IS NULL' )
            ->innerJoin('o.customer', 'c')
            ->addSelect('c')
            ->groupBy('c.id')
            ->orderBy('o.timestamp', 'DESC')
            ->getQuery()
            ->getResult();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 2013-05-14
      • 1970-01-01
      • 2012-09-23
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      相关资源
      最近更新 更多