简体   繁体   English

使用条件和/或投影(子查询)将SQL转换为休眠查询

[英]Convert SQL to hibernate query using criteria and/or projection (subqueries)

Could anyone please help to convert this SQL Query to HQL (using criteria and projection) to have in result Set<topic> topics . 任何人都可以帮助将此SQL查询转换为HQL(使用条件和投影)以包含在结果Set<topic> topics

SELECT t.id, t.title, COUNT(p.id) as count, MAX(p.created_on) as `latest`
FROM topics t
JOIN posts p
  ON t.id = p.topic_id
GROUP BY t.id
ORDER BY count ASC;

My problem is that Hibernate is fetching all data connected to one of columns of the topic table (connected table is users ) - and query takes to much time and unnecessary selects and joins. 我的问题是Hibernate正在获取连接到topic表的某一列(连接的表是users )的所有数据-查询要花费大量时间,并且不必要地进行选择和联接。
Tried to use projections but couldn't. 尝试使用投影,但不能使用。
Thanks in advance for any help! 在此先感谢您的帮助!

From your code, 根据您的代码,

SELECT t.id, t.title, COUNT(p.id) as count, MAX(p.created_on) as `latest`
FROM topics t
JOIN posts p
  ON t.id = p.topic_id
GROUP BY t.id
ORDER BY count ASC;

You can remove JOIN and convert it in WHERE condition. 您可以删除JOIN并将其转换为WHERE条件。 Hope it will save you. 希望它能拯救您。

Use this following code 使用以下代码

SELECT t.id, t.title, COUNT(p.id) as count, MAX(p.created_on) as `latest`
FROM topics t, posts p
WHERE t.id = p.topic_id
GROUP BY t.id
ORDER BY count ASC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM