在学说查询中,我如何才能group by
复合主键中的某些变量?在下面的例子中,Category
和 Product
(但不是 Iterator
)?
例子
下表应保留价格随时间变化的历史记录(交易
)。我正在尝试编写一个学说查询以返回最新日期的记录(在引用日期之前):
Category (PK) | Product (PK) | Iterator (PK) | CreateDT | Amount
1 1 1 2016-01-01 100
1 1 2 2016-04-01 150
1 2 1 2016-09-01 50
2 1 1 2016-01-01 75
2 1 2 2016-01-31 80
2 1 3 2016-09-01 90
使用以上作为引用,我试图获得的结果是每个类别/产品一条记录,如下所示:
一个)。考虑 Category=1
并与引用日期 2016-02-01
进行比较:
Category (PK) | Product (PK) | Iterator (PK) | CreateDT | Amount
1 1 1 2016-01-01 100
1 2 1 2016-09-01 50
b).仅与引用日期 2016-02-01
进行比较:
Category (PK) | Product (PK) | Iterator (PK) | CreateDT | Amount
1 1 1 2016-01-01 100
1 2 1 2016-09-01 50
2 1 2 2016-01-31 80
代码
我的尝试是在下面,但它不起作用(在理想的世界中,我希望 `$category 是可选的):
public function findActiveIterationByDate($category, $refdate)
{
return $this->getEntityManager()
->createQuery(
'SELECT b3
FROM AppBundle:Transaction t1
INNER JOIN
(SELECT t2
FROM AppBundle:Transaction t2, max(createDT) as createDT
WHERE t2.Category=$category, t2.createDT <= $refdate
GROUP BY t2.Category, t2.Product) as t3
ON t1.Category=t3.Category AND t1.Product=t3.Product'
)
->getResult();
}
错误
但是,尝试这样做会出现以下错误 - 我不确定问题是我的 INNER JOIN 还是 DQL 无法按部分主键分组?
[Doctrine\ORM\Query\QueryException]
[Semantical Error] line 0, col 102 near '(SELECT t2
': Error: Class '(' is not defined.
最佳答案
错误是因为您不能在JOIN
语句中使用子查询。你可以在 DQL syntax declartation 中看到它.更具体地说,Join
和 JoinAssociationDeclaration
定义。
我认为您可以将 INNER JOIN
语句移动到 SELECT
子查询中,并尽可能使 WHERE
条件更具限制性,即使这会可能会降低性能。
也许写一个 Native SQL 会更好并将结果映射到相对简单且有据可查的 Doctrine 实体。参见 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html#the-resultsetmapping .
关于mysql - 是否可以通过主键的一部分对 DQL 查询进行分组并返回具有 max() 日期时间记录(早于引用日期)的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724361/