【问题标题】:Performing Unions with Ecto与 Ecto 进行联合
【发布时间】:2022-01-05 02:06:52
【问题描述】:

我正在我的 Phoenix 应用程序中的三个表上运行搜索功能,我想使用 SQL 的 UNION 运算符之类的东西加入它们。

我有三张桌子:

mix phx.gen.json Accounts User users handle:string email:string
mix phx.gen.json Content Post posts title:string content:string
mix phx.gen.json Content Category categories name:string

假设没有外键或链接表。

如果我想在 SQL 中对这些内容进行搜索,我会这样做:

SELECT handle FROM users WHERE handle LIKE "%string%"
UNION
SELECT title FROM posts WHERE title LIKE "%string%"
UNION
SELECT name FROM categories WHERE name LIKE "%string%"

但是,Ecto 2 似乎不支持工会。我想做这样的事情:

query1 =
  from u in User,
    where: ilike(u.handle, ^"%#{str}%"),
    select: u

query2 =
  from p in Post,
    where: ilike(p.title, ^"%#{str}%"),
    select: p

query3 =
  from c in Category,
    where: ilike(c.name, ^"%#{str}%"),
    select: c

union = Ecto.SomethingLikeAUnion([query1, query2, query3])
result = Repo.all(union)

最好的方法是什么?

【问题讨论】:

  • 不是你问的,但是......这是我经常使用 Elasticsearch 之类的东西的情况。它在搜索方面做得更好,并且 UNION 将不是问题。不过,如果您犹豫是否要为您的应用添加额外的技术,这完全可以理解。

标签: elixir union phoenix-framework ecto


【解决方案1】:

Ecto doesn't support unions at the moment. 在 Ecto 添加对联合的支持之前,最好的方法是将原始 SQL 与 Repo.query/2 一起使用:

MyApp.Repo.query("""
  SELECT handle FROM users WHERE handle LIKE $1
  UNION
  SELECT title FROM posts WHERE title LIKE $1
  UNION
  SELECT name FROM categories WHERE name LIKE $1
""", ["%#{str}%"])

【讨论】:

    【解决方案2】:

    似乎添加了 UNION 和 UNION ALL here

    并记录在here

    supplier_query = from s in Supplier, select: s.city
    from c in Customer, select: c.city, union: ^supplier_query
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多