【问题标题】:What is the proper syntax for an Ecto query using ilike and SQL concatenation?使用 ilike 和 SQL 连接的 Ecto 查询的正确语法是什么?
【发布时间】:2021-08-17 21:33:35
【问题描述】:

我正在尝试进行 Ecto 查询,在其中连接给定查询结果的名字和姓氏,然后使用查询字符串执行 ilike 搜索。例如,我可能想在数据库中搜索所有以“Bob J”开头的名字。目前,我的代码如下所示:

pending_result_custom_search = from result in pending_result_query,
         where: ilike(fragment("CONCAT(?, '',?)", result.first_name, result.last_name), ^query)

(pending_result_query 是我正在编写的上一个查询)

这种方法不起作用,我继续得到一个空的查询集。如果我执行这样的查询

query = "Bob"
pending_result_custom_search = from result in pending_result_query,
         where: ilike(fragment("CONCAT(?, '',?)", "%Bob%", ""), ^query)

我得到了正确的功能。

使第一种方法正常工作的正确语法是什么?

【问题讨论】:

    标签: sql elixir ecto phoenix


    【解决方案1】:

    我认为在你的情况下我只会使用fragment,例如

    query = "%" <> "Bob" <> "%"
    pending_result_custom_search = from result in pending_result_query,
             where: fragment("first_name || last_name ILIKE = ?", ^query)
    

    这样您就可以将焦点转移到 PostGres 并使用它的函数,而不必过多担心它们的 Ecto 抽象。在上面的示例中,我使用|| 连接列值,但如果需要,您可以使用 PostGres 的CONCAT():

    pending_result_custom_search = from result in pending_result_query,
             where: fragment("CONCAT(first_name, last_name) ILIKE = ?", ^query)
    

    请注意,这里的两个示例都没有在first_name 和last_name 之间包含空格。另外,我在绑定之前将% 字符添加到搜索查询中。

    【讨论】:

    • 您还可以在这里尝试什么?这会导致语法错误:` ERROR 42601 (syntax_error) syntax error at or near "=" (CONCAT(first_name, last_name) ILIKE = 'Alex') ` 看起来它没有识别 first_name和实际查询中的 last_name 字段。例如,在同一个查询中,我查看订单状态,错误代码显示此 t0."order_status",您可以看到它实际上是在尝试从查询中访问 order_status 而不是什么first_name 和 last_name 发生
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多