【问题标题】:Staggered/phased/conditional SQL building in jOOQjOOQ 中的交错/分阶段/条件 SQL 构建
【发布时间】:2016-06-08 09:10:51
【问题描述】:

有没有办法使用 jOOQ 分阶段/阶段构建 SQL?比如:

        DSLContext create = DSL.using(conn, SQLDialect.MYSQL);
        DSL dsl = create.from(table("links"));
        if( !StringUtils.isEmpty(place) ) { // place is specified, change the query

            long placeId = getPlaceId();

            if (placeId > 0) {
                            dsl = create.from(table("place_links"))
                            .join(table("links"))
                            .on(field("links.id").equal(field("place_links.link_id")))
                            .where(field("place_links.place_id").equal(placeId));
            }
        }

        String sql = dsl.select(field("*"))
               .orderBy("links.score")
               .limit(1)
               .getSQL();

以上内容无法编译,但我正在寻找类似原则的东西。我需要从from 开始,因为目标表在运行时会发生变化。

要求是最终查询在运行时根据输入的值发生变化。

【问题讨论】:

    标签: java sql jdbc jooq


    【解决方案1】:

    如果您立即开始构建SELECT 语句,SQL 感觉不是一种非常可组合的语言。但是,如果您将不同的子句视为动态的构建块,那么事情会立即变得简单得多。在你的情况下:

    Table<?> from = table("links");
    Condition where = trueCondition();
    
    if (!StringUtils.isEmpty(place)) {
        long placeId = getPlaceId();
    
        if (placeId > 0) {
            from = from.join("place_links").on("links.id = place_links.link_id");
            where = where.and("place_links.place_id = ?", placeId);
        }
    }
    
    DSL.using(conn)
       .selectFrom(from)
       .where(where)
       .orderBy(field("links.score"))
       .limit(1)
       .fetch();
    

    以上是假设

    import static org.jooq.impl.DSL.*;
    

    更多关于如何使用 jOOQ 动态构建 SQL 语句的描述如下: http://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql

    【讨论】:

    • 相当聪明。我刚刚在if (placeId &gt; 0) { 之后编辑了正确的行。我想你的意思是from,但写了table。其他一切看起来都很棒。
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多