你不可错过的原始SQL来Repo.all这样。
最好你可以做的是通过一些不支持的数据库功能作为片段或找到解决方法。
#UNION ALL
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> result1 ++ result2
["a", "b", "a", "c"]
#UNION
iex(1)> result1 = Model1 |> select([m], m.title) |> Repo.all
["a", "b"]
iex(2)> result2 = Model2 |> select([m], m.title) |> Repo.all
["a", "c"]
iex(3)> (result1 ++ result2) |> Enum.uniq
["a", "b", "c"]
#UNION USING RAW SQL
iex(1)> query = "select title from models1 union select title from model2"
...
iex(2)> {:ok, %Postgrex.Result{columns: columns, rows: rows}} = Ecto.Adapters.SQL.query(Repo, query, [])
...
iex(3)> rows |> Enum.map(&Enum.zip(columns, &1)) |> Enum.map(&Enum.into(&1, %{}))
[%{"title" => "a"}, %{"title" => "b"}, %{"title" => "c"}]
您是否正在尝试创建'Ecto'不提供的高级SQL查询?例如, – TheAnh
是,联合查询。 –