Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 带条件where的EXTO片段子查询_Sql_Elixir_Ecto - Fatal编程技术网

Sql 带条件where的EXTO片段子查询

Sql 带条件where的EXTO片段子查询,sql,elixir,ecto,Sql,Elixir,Ecto,我正在尝试使用EXTO执行一个查询,其中一个子查询作为选择项。在SQL中,该玩家似乎拥有很多选票: 选择 players.id作为player\u id, 从投票中选择count*,其中vots.player\u id=players.id作为投票计数 从…起 球员 但是,根据参数的存在,我希望SELECT子查询有一个额外的WHERE子句。例如 SELECT players.id AS player_id, (SELECT count(*) FROM votes WHERE vo

我正在尝试使用EXTO执行一个查询,其中一个子查询作为选择项。在SQL中,该玩家似乎拥有很多选票:

选择 players.id作为player\u id, 从投票中选择count*,其中vots.player\u id=players.id作为投票计数 从…起 球员 但是,根据参数的存在,我希望SELECT子查询有一个额外的WHERE子句。例如

SELECT
    players.id AS player_id,
    (SELECT count(*) FROM votes WHERE votes.player_id = players.id AND votes.type = 'motm') AS vote_count
FROM
    players
在《星外》中,我提出了以下观点:

vote_count_query =
  from(p in Player,
    select: %{
      player_id: p.id,
      vote_count:
        fragment(
          "SELECT count(*) FROM votes WHERE votes.player_id = ?",
          p.id
        )
    }
  )
假设有一个变量vote_类型可能是或可能不是nil,我如何有条件地将where子句添加到内部select子查询中?例如

fragment(
  "SELECT count(*) FROM votes WHERE votes.player_id = ? AND votes.type = ?",
  p.id,
  ^vote_type
)
如果有更好的方法来统计所有球员的票数,那么我很高兴听到这个消息。使用连接时,似乎不返回没有投票权的玩家。

虽然@dogbert看起来可能有用,但我通过用左连接替换SELECT子查询来实现这一点:

def vote_count(team_id, vote_type \\ nil) do
  vote_count_query =
    Player
    |> select([p, v], %{
      player_id: p.id,
      vote_count: count(v.id)
    })
    |> where([p, _], p.team_id == ^team_id)
    |> group_by([p, _], p.id)

  # depending on whether we are filtering by vote_type use the appropriate join
  # condition
  if(is_nil(vote_type),
    do: vote_count_query |> join(:left, [p], v in assoc(p, :votes)),
    else:
      vote_count_query
      |> join(:left, [p], v in Vote, on: p.id == v.player_id and v.type == ^vote_type)
  )
end
似乎关键是在连接条件中使用左外部连接和投票类型,而不是默认的内部连接。否则,结果中不会返回票数为0的玩家。

fragmentSELECT count*FROM vows.player\u id=?和是否为NULL或vots.type=?,p.id,^vote\u type,^vote\u type?