用于从组中选择具有最大值的行的Hql或Criteria

时间:2012-04-10 10:27:27

标签: grails hql gorm criteria

我需要编写一个条件或HQL,只选择InterfaceVersion并使用每个interfaceCode的最新版本。版本由majorVersion.minorVersion.editVersion组成。

为例:

InterfaceVersion表:

id | interface_code_id | major_version | minor_version | edit_version
---|-------------------|---------------|---------------|-------------
 1 |                 1 |             1 |             1 |            6
 2 |                 1 |             1 |             5 |            0
 3 |                 2 |             1 |             0 |            0
 4 |                 2 |             0 |             1 |            0
 5 |                 2 |             2 |             0 |            1
 6 |                 2 |             1 |             3 |            6

预期结果将是:

InterfaceVersions instances with ids [2, 5]

我有这个GORM域类(简化):

InterfaceCode{
    int id
    String code

    static hasMany = [ versionList: InterfaceVersion]
}

InterfaceVersion{
    int id
    InterfaceCode interfaceCode
    int majorVersion
    int minorVersion
    int editVersion

    static belongsTo = [ InterfaceCode ]

    static constraints = {
        interfaceCode(unique:['majorVersion','minorVersion','editVersion'])
    }
}

到目前为止,我已经能够提出这个sql:

SELECT t1.*
FROM Interface_Version  t1
  Left Outer Join Interface_Version  T2
    On (T1.Interface_Code_Id = T2.Interface_Code_Id And 
      (T1.Major_Version < T2.Major_Version Or 
      (T1.Major_Version = T2.Major_Version And T1.Minor_Version < T2.Minor_Version) Or 
      (T1.Major_Version = T2.Major_Version And T1.Minor_Version = T2.Minor_Version And T1.Edit_Version < T2.Edit_Version ) )
      )
WHERE t2.id IS NULL

你能把这个sql转换成hql或critearia还是想出更好的东西?

0 个答案:

没有答案