我有一段时间试图弄清楚这个HQL语句。我试图获取组内所有产品订单的最新状态,但似乎无法找出正确的HQL语法以使其正常工作......
示例表:
id | created_at | group_id | purchase_id | status
---|------------|----------|-------------|------------
0 | 10 | 3 | 6 | DELIVERING
1 | 11 | 3 | 6 | DELIVERED
2 | 12 | 3 | 7 | DELIVERING
3 | 13 | 3 | 8 | DELIVERING
4 | 14 | 4 | 13 | DELIVERING
5 | 15 | 4 | 13 | DELIVERED
6 | 16 | 4 | 13 | LOST
7 | 17 | 5 | 17 | DELIVERING
获取每个created_at
的最新信息(purchase_id
),其中group_id
= 3.应该在此表中生成:
id | created_at | group_id | purchase_id | status
---|------------|----------|-------------|------------
1 | 11 | 3 | 6 | DELIVERED
2 | 12 | 3 | 7 | DELIVERING
3 | 13 | 3 | 8 | DELIVERING
在PostgreSQL中运行的查询:
SELECT DISTINCT ON (o.purchase_id) *
FROM orders o
WHERE o.group_id = 3
ORDER BY o.purchase_id, o.created_at DESC
等效的HQL语句是什么?
答案 0 :(得分:1)
假设每个created_at
中的purchase_id
值是唯一的,那么下面的HQL应该有效
from Orders
WHERE (purchase_id, created_at)
IN
( SELECT purchase_id, max( created_at )
FROM Orders
GROUP BY purchase_id
)
当created_at
对于给定的purchase_id
不唯一时(purchase_id的一个值可能有两个具有相同值created_at
的“最新”记录),那么更深的子查询级别是必需的 - 以下HQL将只为每个created_at
选择一个记录最高id
然后最高purchase_id
的记录(这次假设该ID是主键并且是唯一的):
from Orders
WHERE id IN (
SELECT max( id ) from Orders
WHERE (purchase_id, created_at)
IN (
SELECT purchase_id, max( created_at )
FROM Orders
GROUP BY purchase_id
)
GROUP BY purchase_id
)