2014-02-20 51 views
0

以下是一个SQL查询,我希望hql查询相同??任何建议,将不胜感激。sql查询的HQl查询?

在这个查询中,我试图抓取两张表'blogs'和'askquestions'的记录,这些记录没有与eachother映射。

SELECT blog_title as title ,created_date as date FROM blog UNION SELECT ask_question as title , created_on as date FROM askquestions) as aa ORDER BY date DESC 

回答

0

不幸HQL不支持UNIONUNION ALL作为尚未。

你仍然可以尝试以下解决办法:

// Create two query strings for two sub HQLs 
String firstHQLQueryStr = " from blog b where <criteria1>"; 
String secondHQLQueryStr = "from askquestions a where <criteria2>"; 

// Divide the two select clauses into two sub HQLs 
Query query1 = session.createQuery(firstHQLQueryStr); 
Query query2 = session.createQuery(secondHQLQueryStr); 

// Fetch the data from database using these two sub HQLs first 
List firstDataList= query1.list(); 
List secondDataList= query2.list(); 

//Combine the results 
firstDataList.add(secondDataList); 

// Collection equivalent to UNION ALL 
List nonUniqueCollection = firstDataList; 

//Collection equivalent to Union (as non-unique elements are removed) 
HashSet uniqueCollection = new HashSet(nonUniqueCollection); 

希望有所帮助。

+0

我觉得这种方式是不可能的,因为我想根据日期打印的清单(日期列在两个表中存在)。而最新的一个必须是先打印,后面打印。 – User2413

+0

的确如此,但是遗憾的是没有其他选择,因为它尚未作为HQL的支持添加。这也被提出[在这里](https://hibernate.onjira.com/browse/HHH-1050)。 –

0

尝试像这样...

select * from ((blog_title as title ,created_date as date FROM blog) union (SELECT ask_question as title , created_on as date FROM askquestions)) as a order by a.date desc;