HQL:使用 where-in-subselect 构造获取完整行时如何保持排序顺序?

发布于 2024-10-16 23:45:07 字数 695 浏览 4 评论 0原文

我目前正在创建一个类似“其他喜欢这个的人也喜欢”的功能。

相关 HQL 语句返回产品 ID 列表(按两个产品之间共享“喜欢”的数量排序)。但结果并不明显 - 精简到最基本的内容,查询看起来像这样。 (请注意:这不是原始查询,而是一个简化的示例,让您了解我在做什么)

select prd2.id from UserLike ul2
join ul2.product prd2
where ul.userId in (
    select ul.userId from UserLike ul
    join ul.product prd
    where prd.id=:productId
)
group by prd2.id
order by count(prd2.id) desc

从那里开始,是否有一个通用模式来检索每个产品的完整行/实体?

在 SQL 中,我将使用上面的查询作为 FROM 中的子选择并连接回产品表。

由于 HQL 不支持 FROM 中的子选择,因此我认为除了换行之外没有其他方法

from product p where p.id in (SUBSELECT_AS_ABOVE)

,但会进行排序。 :(

也许这听起来有点奇怪,但我认为这是一个常见的用例 - 那么有没有常见的解决方法?

提前非常感谢,并致以最诚挚的问候, 彼得

I am currently creating a feature like 'other people who liked this also like'.

The HQL statement in question returns a list of product ids (ordered by count of shared 'likes' between two products). But the result is not distinct - stripped down to the very basics, the query looks something like this. (Please note: it's not the original query, rather a simplified example to give you an idea of what I am doing)

select prd2.id from UserLike ul2
join ul2.product prd2
where ul.userId in (
    select ul.userId from UserLike ul
    join ul.product prd
    where prd.id=:productId
)
group by prd2.id
order by count(prd2.id) desc

Starting from there, is there a common pattern to retrieve the complete row/entity for each product?

In SQL I'd use the query above as a subselect within FROM and join back to the product table.

As HQL does not support subselects within FROM, I do not think there is another way than to wrap

from product p where p.id in (SUBSELECT_AS_ABOVE)

but there goes the sorting. :(

Maybe this sounds a bit weird, but I think this is a common use case - so are there any common workarounds for this?

Thanks a lot in advance and best regards,
Peter

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏雨一样淡蓝的深情 2024-10-23 23:45:07

您可以分两步完成:
1. 获取 ID 列表(您已经完成了);
2. 根据ID列表获取所有产品。
您可以使用 Expression.In("Id", idList) 来执行此操作,其中 idList 是第一个查询的 IList 结果。

另外,如果可能的话,尝试在没有 HQL 的情况下做所有事情,但有标准和限制。

You can do it in two steps:
1. Get list if IDs (which you have already done);
2. Get all products by IDs list.
You can do that with Expression.In("Id", idList) where idList is IList result from first query.

Also, if only possible, try to do everything w/o HQL but with criteria and restrictions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文