【问题标题】:How to use 'LIKE' function to select array of Strings with JOOQ如何使用“LIKE”函数通过 JOOQ 选择字符串数组
【发布时间】:2017-05-24 07:08:28
【问题描述】:

我现在想在 JOOQ 中使用 'like' 函数来选择数据,包括不区分大小写和部分匹配的字符串数据数组。

表架构是:

CREATE TABLE favorites (
    id int,
    items    varchar(100)[]
);

样本数据是:

INSERT INTO favorites (id, items)
    VALUES (1, '{orange, lemon, banana}');
INSERT INTO favorites (id, items)
    VALUES (2, '{apple, grape}');

要获取第一条数据,SQL 是这样的:

SELECT id, items FROM favorites WHERE 'orange' = ANY (items);

我的目标是通过区分大小写和部分匹配来选择数据,例如:例如,使用 likeIgnoreCase("OraNge") 或 like("%ang%") ?

使用 LIKE 功能开发以下代码:

Connection connection = ...;
DSLContext context = DSL.using(connection, ...);
List<Table> table = context.select().from(TABLE).fetchInto(Table.class);

如何使用like函数?

在此先感谢您。

【问题讨论】:

    标签: java sql postgresql jooq


    【解决方案1】:

    PostgreSQL value = ANY (array) 运算符无法匹配 LIKE 谓词之类的值。您将需要使用实际的 LIKE 谓词。在 SQL 中,你会写:

    SELECT id, items
    FROM favorites
    WHERE EXISTS (SELECT * FROM unnest(items) AS t(item) WHERE item ILIKE '%OraNge%')
    

    或者,使用 jOOQ:

    context.select(FAVORITES.ID, FAVORITES.ITEMS)
           .from(FAVORITES)
           .whereExists(
                selectFrom(unnest(FAVORITES.ITEMS).as("t", "item")
               .where(field(name("item", String.class)).likeIgnoreCase("%OraNge"))
           )
           .fetch();
    

    jOOQ 版本一如既往地假设您有这个静态导入:

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

    【讨论】:

      【解决方案2】:

      此外,这里有几种使用 LIKE 的方法。您始终可以使用 jOOQ LIKE 谓词,请参阅他们的文档。在我的第二个示例中,我在字符串中使用 sql 语法,只是为了证明你可以。您也可以像使用字符串一样使用 contains/startsWith/endsWith。

      jooq.dsl()
        .select()
        .from(MY_TABLE)
        .where(Employee.EMPLOYEES.LAST_NAME.like("ER")));
      
      jooq.dsl()
        .select()
        .from(EMPLOYEES)
        .where(Employee.EMPLOYEES.LAST_NAME.like("ER"))
        .and("first_name like ?", "ST"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        相关资源
        最近更新 更多