我有一个MySQL数据库,其中存储了某些项目的销售。我想比较过去两天的销售情况,例如:过去10天和过去9天。我计算出MySQL查询:
select s1.sales - s2.sales from ProductSales as s1
left join ProductSales as s2 on s2.date >= DATE(DATE_ADD(Now(), INTERVAL '-10' DAY)) and s2.date <= DATE(DATE_ADD(Now(), INTERVAL '-9' DAY)) and s2.product_id = s1.product_id
where s1.date >= DATE(DATE_ADD(Now(), INTERVAL '-9' DAY));
我想在Grails应用程序中以编程方式执行此操作,我需要将此查询转换为条件或HQL查询。我该怎么做?
更新:我试过这样:
def date1 = new Date() - 2
def date2 = new Date() - 1
def sales = ProductSales.executeQuery( """
select s1.sales - s2.sales from ProductSales s1
left join ProductSales s2
where s1.date >= :date2
and s2.date >= :date1 and s2.date < :date2 and s2.product_id = s1.product_id""",
[ date1: date1, date2: date2 ] )
不幸的是,这给了我:
ERROR hql.ast.ErrorCounter - Path expected for join!
ERROR hql.ast.ErrorCounter - Invalid path: 's2.sales'
ERROR hql.ast.ErrorCounter - right-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter - Invalid path: 's2.date'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter - left-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter - Invalid path: 's2.date'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter - left-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter - Invalid path: 's2.product_id'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter - left-hand operand of a binary operator was null
ERROR logging.impl.SLF4JLog - QuerySyntaxException occurred when processing request: [GET] /app/dashboard
Path expected for join!
更新2 :由于我无法回答我自己的问题,我在此处添加回复:
显然这可以正常运作:
def now = new Date()
def date1 = now - 2
def date2 = now - 1
def sales = ProductSales.executeQuery( """
select s1.owner, s1.sales - s2.sales from ProductSales s1, ProductSales s2
where s1.date >= :date2 and s1.date < :now
and s2.date >= :date1 and s2.date < :date2 and s2.product = s1.product""",
[ date1: date1, date2: date2, now: now ]
)
我不完全确定left join
和select from T1, T2
之间有什么区别。从那里开始,我为最近的条目添加了上限(now
),并将product_id
更改为product
。
答案 0 :(得分:0)
显然这可以正常运作:
def now = new Date()
def date1 = now - 2
def date2 = now - 1
def sales = ProductSales.executeQuery( """
select s1.owner, s1.sales - s2.sales from ProductSales s1, ProductSales s2
where s1.date >= :date2 and s1.date < :now
and s2.date >= :date1 and s2.date < :date2 and s2.product = s1.product""",
[ date1: date1, date2: date2, now: now ]
)
我不完全确定left join
和select from T1, T2
之间有什么区别。从那里开始,我为最近的条目添加了上限(now
),并将product_id
更改为product
。