mysql - Doctrine - QueryBuilder - 获得结果中最年轻的实体

标签 mysql doctrine-orm greatest-n-per-group

我有这个表结构:

CREATE TABLE `inventory_item` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `articleID` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

我有这个查询:

$rows = $this->getModelManager()->createQueryBuilder()
            ->select('ii')
            ->from(InventoryItem::class, 'ii')
            ->where('ii.articleId IN (:articleIds)')
            ->andWhere('ii.quantity > 0')
            ->orderBy('ii.date', 'ASC')
            ->setParameter('articleIds',  $articleIds )
            ->getQuery()
            ->getResult();

在数据库中,我可以拥有如下所示的实体:

ID | ArticleID | Quantity | Date
1  | 100       |     10    | 2018-08-31
2  | 200       |     20    | 2018-07-31
3  | 100       |     40    | 2018-05-31

现在,当查询中的 $articleIds 为 100、200 时,我希望得到以下输出:

ID | ArticleID | Quantity | Date
2  | 200       |     20    | 2018-07-31
3  | 100       |     40    | 2018-05-31

因此,当 ArticleID 相等时,查询应仅返回具有最年轻日期的实体,以及 ArticleId = 200 的实体。

学说查询构建器是否有可能实现这一目标?我尝试使用 groupBy,但这不起作用,因为使用 groupBy 时 orderBy 对结果没有影响。

谢谢!

最佳答案

您可以按DESC 排序并告诉 Doctrine 为 return max 一个结果,例如:

$query = $this->getModelManager()->createQueryBuilder()
            ->select('ii')
            ->from(InventoryItem::class, 'ii')
            ->where('ii.articleId IN (:articleIds)')
            ->andWhere('ii.quantity > 0')
            ->orderBy('ii.date', 'DESC')
            ->setParameter('articleIds',  $articleIds )
            ->getQuery();

$result = $query
->setMaxResults(1)            
->getResult();

希望对你有帮助

关于mysql - Doctrine - QueryBuilder - 获得结果中最年轻的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569878/

相关文章:

php - 优化内存资源以响应大查询

mysql - 选择最新的行以及恰好 2 行具有一个条件的行和 2 行具有不同条件的行

mysql - 显示符合条件的最新ID

php - 教义一对一单向错误拯救 child

mysql_?相当于PDO的prepare()和execute()

mysql - 第 2 行 SQL 语法错误

php - 如何根据列字段的计数选择记录

php - Symfony2 Doctrine 元数据缓存与 Redis 问题

sql - 从每个组中返回具有最新时间戳的行

php - 缩略图分页的想法