代码之家  ›  专栏  ›  技术社区  ›  Bitwise

使ECO查询更高效

  •  2
  • Bitwise  · 技术社区  · 8 年前

    我正在尝试查看当前用户的团队是否与传入用户的团队重叠。我有一些有用的东西,但我很好奇它是否能让我更有效率。以下是我的资料:

    user_teams = from(
      t in MyApp.Team,
      left_join: a in assoc(t, :accounts),
      where: p.owner_id == ^user.id or (a.user_id == ^user.id and t.id == a.project_id)
    ) |> Repo.all
    
    current_user_teams = from(
      t in MyApp.Team,
      left_join: a in assoc(t, :accounts),
      where: t.owner_id == ^current_user.id or (a.user_id == ^current_user.id and p.id == a.project_id)
    ) |> Repo.all
    

    然后我将它们与:

    Enum.any?(user_teams, fn(t) -> t in current_user_teams end)
    

    同样,这符合我的需要,但似乎有一个更好的方法来做到这一点?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Hauleth    8 年前

    最简单的解决方案是将这两个查询合并为一个查询,并检查结果查询是否返回任何内容。所以,让我们这么做:

    query = from t in MyApp.Team,
      left_join: a in assoc(t, :accounts),
      where: p.owner_id == ^user.id or (a.user_id == ^user.id and t.id == a.project_id),
      where: t.owner_id == ^current_user.id or (a.user_id == ^current_user.id and p.id == a.project_id),
      limit: 1,
      select: true
    
    not is_nil(Repo.one(query))
    

    这将模拟 SELECT EXIST (…) 从PostgreSQL查询(在第3.0版中 Repo.exist?/1 这样做的功能, related issue )

    复制的 where 碎片将 AND 默认情况下的ED。