【问题标题】:jOOQ - error with alias and quotesjOOQ - 别名和引号错误
【发布时间】:2014-11-16 11:55:53
【问题描述】:

我有这个问题:

Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
                    String.class, LICENZE.CREATION_DATE).as("anno_mese");

List<Record3<Integer, String, String>> records = 
    create.select(DSL.count().as("num_licenze"), LICENZE.EDIZIONE, yearMonth).
    from(LICENZE).
    groupBy(LICENZE.EDIZIONE, yearMonth).
    orderBy(yearMonth).
    fetch();

此查询生成:

select 
  count(*) "num_licenze", 
  "PUBLIC"."LICENZE"."EDIZIONE", 
  FORMATDATETIME("PUBLIC"."LICENZE"."CREATION_DATE", 'yyyy-MM') "anno_mese"
from "PUBLIC"."LICENZE"
group by 
  "PUBLIC"."LICENZE"."EDIZIONE", 
  "anno_mese"
order by "anno_mese" asc

执行它我得到:Column "anno_mese" not found; SQL statement

测试生成的查询并在查询的每个部分中删除 anno_mese 中的引号,以使查询正常工作。

是我的查询错误还是我以错误的方式使用了 jooq?

这个查询中的别名并不那么重要,我也可以不使用它来运行查询,只是为了了解它是如何工作的。 我使用 h2 作为数据库。

感谢您的帮助

【问题讨论】:

    标签: java sql h2 jooq


    【解决方案1】:

    I suspect this is a bug in H2, which I've reported here,因为查询对我来说很好。以下是您可以从 jOOQ 方面执行的一些解决方法:

    不要按名称引用 "anno_mese"

    虽然 SQL 在其他方面有些重复,但您不会注意到与 jOOQ 的区别。我只是将as("anno_mese") 方法调用移到SELECT 子句中。在GROUP BYORDER BY 子句中你并不需要它。

    Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
                        String.class, LICENZE.CREATION_DATE);
    
    List<Record3<Integer, String, String>> records = 
        create.select(DSL.count().as("num_licenze"), 
                      LICENZE.EDIZIONE, 
                      yearMonth.as("anno_mese")).
        from(LICENZE).
        groupBy(LICENZE.EDIZIONE, yearMonth).
        orderBy(yearMonth).
        fetch();
    

    在 jOOQ 生成的查询中禁用引用

    您可以使用jOOQ's Settings 来阻止schema / table / column names from being quoted。示例:

    DSLContext create = DSL.using(connection, SQLDialect.H2, 
        new Settings().withRenderNameStyle(RenderNameStyle.AS_IS);
    

    使用大写的列名

    这可能会起作用:DSL.field(...).as("ANNO_MESE")

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2014-11-05
      • 2017-09-26
      • 2013-12-05
      • 2020-12-31
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多