hibernate 将合并两个查询合并为一个查询

fcwjkofz  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(139)

在第一个查询中,我需要获得每个类型的计数,而不管它是否已读(未读可以是true或false)。在第二个查询中,我只需要unread为false时所有类型的计数。目前我调用数据库两次,一次是第一个查询,一次是第二个查询。有没有什么方法可以让我只调用一次数据库来获得两个查询的结果?
请注意,我的查询是在HQL,我写了他们的SQL版本B/C,我认为它更容易;所以理想情况下,我需要有一个解决方案,为HQL工作了。谢谢.

--Need the count regardless if is_read is true or false. 
--In order to get total of all rows, I add up each total for each group in the Java code:

select type_id as type, count(distinct ta.id) as totalId 
  from tableA as ta 
       inner join tableB tb on ta.id = tb.id 
       inner join tableC tc on tb.col1= tc.col2 
 where tc.col2= 6 
   and tb.is_deleted = 'N' 
 group by type_id 
--Need the count only for is_read = false. 
--This query gives the total for all unread rows so no group by needed:
    
select count(distinct ta.id) as totalId 
  from tableA as ta 
       inner join tableB tb on ta.id =tb.id 
       inner join tableC tc on tb.col1 = tc.col2 
 where tc.col2= 6 
   and tb.is_deleted = 'N'
   and tb.is_read = 'N'
hl0ma9xz

hl0ma9xz1#

你可以试试这个

SELECT 
ta.typeId AS type,
COUNT(DISTINCT ta.id) AS totalId,
COUNT(DISTINCT CASE WHEN tb.isRead = 'N' THEN ta.id END) AS unreadTotalId
FROM 
TableA ta 
INNER JOIN 
ta.tableB tb 
INNER JOIN 
tb.tableC tc  
WHERE 
tc.col2 = 6 AND tb.isDeleted = 'N' 
GROUP BY 
ta.typeId;

相关问题