fir*_*iel 5 grails criteria grails-orm
我正在使用Grails 1.2.4.我想知道如何通过"countDistinct"(降序)和在投影中使用groupProperty进行排序.
这是我的域名:
class Transaction {
static belongsTo = [ customer : Customer, product : Product ]
Date transactionDate = new Date()
static constraints = {
transactionDate(blank:false)
}
}
class Product {
String productCode
static constraints = {
productCode(blank:false)
}
}
Run Code Online (Sandbox Code Playgroud)
在MySQL术语中,这就是我想要的:
select
product_id,
count(product_id)
from
transaction
group by
product_id
order by
count(product_id) desc
Run Code Online (Sandbox Code Playgroud)
总的来说,我想获得一个产品列表(或只是产品ID),按产品的交易数量(降序)排序
这是我的猜测:
def c = Transaction.createCriteria() def transactions = c.list {
projections {
groupProperty("product")
countDistinct("product")
}
maxResults(pageBlock)
firstResult(pageIndex) }
def products = transactions.collect { it[0] }
Run Code Online (Sandbox Code Playgroud)
但它没有给出我预期的结果.任何领导都将受到高度赞赏.谢谢!
试试这个:
def c = Transaction.createCriteria()
def transactions = c.list {
projections {
groupProperty("product")
countDistinct("id")
}
maxResults(pageBlock)
firstResult(pageIndex)
}
Run Code Online (Sandbox Code Playgroud)
您的条件查询实际上相当于:
select
product_id,
count(**distinct** product_id)
from
transaction
group by
product_id
order by
count(product_id) desc
Run Code Online (Sandbox Code Playgroud)
注意截然不同.您希望计算每个产品的不同事务的数量,因此计算事务ID(或任何事务属性)更有意义.产品ID恰好在没有distinct子句的情况下工作.
您可以打开超级有用的hibernate SQL日志记录来调试此类问题.它将准确显示您的标准如何转换为SQL.在运行时:
org.apache.log4j.Logger.getLogger("org.hibernate").setLevel(org.apache.log4j.Level.DEBUG)
Run Code Online (Sandbox Code Playgroud)
或者在Config.groovy中抛出:
environments {
development {
log4j = {
debug 'org.hibernate'
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:countDistinct("id", "transactionCount")用作投影并按order("transactionCount")计数排序.