如何在Ecto中创建子查询?

guy*_*997 2 elixir ecto

我有两张桌子; 列表和出价.我想使用Ecto列出所有最高出价高于1且低于10的商品.有关架构和查询的更多信息,请参阅下面的代码.

数据库架构

listings
  id
  name


bids
  listing_id
  amount
Run Code Online (Sandbox Code Playgroud)

program.ex

Repo.all(
  from l in Listing,
  where: (SELECT MAX(amount) FROM bids WHERE listing_id = l.id) > 1 and
         (SELECT MAX(amount) FROM bids WHERE listing_id = l.id) < 10)
Run Code Online (Sandbox Code Playgroud)

怎么会这样呢?

Mik*_*hot 6

作为group_by/ having查询:

Repo.all(
  from l in Listing,
  join: b in assoc(l, :bids),
  group_by: l.id,
  having: (max(b.amount) > 1) and (max(b.amount) < 10)
  select: l)
Run Code Online (Sandbox Code Playgroud)