Staggered/phased/conditional SQL 在 jOOQ 中构建

Staggered/phased/conditional SQL building in jOOQ

有没有办法使用 jOOQ 在 phases/stages 中构建 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 开始,因为目标 table 在运行时发生变化。

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

如果您立即开始构建 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