简体   繁体   English

需要NHibernate中复杂SQL查询的帮助

[英]Need help for complex SQL query in NHibernate

I need to know how I can rewrite the following SQL query in NHibernate's ICriteria format. 我需要知道如何以NHibernate的ICriteria格式重写以下SQL查询。 It is basically a way to mimic the MS-SQL's RANK() feature and return only those results that are most current. 基本上,这是模仿MS-SQL的RANK()功能并仅返回最新结果的一种方法。

SELECT a.Name, a.Value, a.CreationDate
FROM MyTable a
WHERE EXISTS
(
  SELECT NULL
  FROM
  (
    SELECT TOP 1 CreationDate
    FROM MyTable
    WHERE Name = a.Name
    ORDER BY CreationDate DESC
  ) b
  WHERE b.CreationDate = a.CreationDate
)

For example, given a table with the following data: 例如,给定一个包含以下数据的表:

NAME, VALUE, CREATIONDATE 名称,值,创建日期
'Key One', 'value one v1', '2009-11-11' '密钥一','值一v1','2009-11-11'
'Key One', 'value one v2', '2009-11-12' '关键一号','价值一号v2','2009-11-12'
'Key Two', 'value two v1', '2009-11-09' '键二','值二v1','2009-11-09'
'Key Three', 'value three v2', '2009-09-09' '关键三','价值三v2','2009-09-09'
'Key Three', 'value three v1', '2009-09-06' “键三”,“值三v1”,“ 2009-09-06”
'Key Three', 'value three v3', '2009-10-01' “关键三”,“价值三v3”,“ 2009-10-01”

The results of the above query would be: 以上查询的结果将是:

'Key One', 'value one v2', '2009-11-12' '关键一号','价值一号v2','2009-11-12'
'Key Two', 'value two v1', '2009-11-09' '键二','值二v1','2009-11-09'
'Key Three', 'value three v3, '2009-10-01' “关键三”,“价值三v3”,“ 2009-10-01”

When the query to complex, don't use "Criteria API" but "HQL", you can be lose a lot of time to find the right solution with "Criteria API". 当查询复杂时,不要使用“ Criteria API”,而要使用“ HQL”,那么使用“ Criteria API”查找正确的解决方案可能会浪费很多时间。 The query you show can almost be use without change. 您显示的查询几乎可以原样使用。 Look at this : https://www.hibernate.org/hib_docs/nhibernate/html/queryhql.html 看这个: https : //www.hibernate.org/hib_docs/nhibernate/html/queryhql.html

At the end the code generated is, in general, the same with "Criteria API" or "HQL" ... 最后,生成的代码通常与“ Criteria API”或“ HQL”相同。

A piece of code : 一段代码:

StringBuilder query = new StringBuilder();
query.Append("from MyTable where ");
query.Append("DateOfDayStart <= :startDate and DateOfDayEnd >= :endDate ");
IList<MyTable> list = session.CreateQuery(query.ToString())
    .SetDateTime("startDate", startDate)
    .SetDateTime("endDate", endDate)
    .List<MyTable>();
return list;

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

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