尽管
the comment
在@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票的玩家。