【发布时间】:2020-05-19 16:20:44
【问题描述】:
我正在尝试使用 ecto 执行带有子查询的查询作为SELECTs 之一。在 SQL 中它看起来像这样 (player has_many votes):
SELECT
players.id AS player_id,
(SELECT count(*) FROM votes WHERE votes.player_id = players.id) AS vote_count
FROM
players
但是,根据参数的存在,我希望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
在ecto中,我想出了这个:
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_type 可能是也可能不是nil,我如何有条件地将where 子句添加到内部选择子查询?例如
fragment(
"SELECT count(*) FROM votes WHERE votes.player_id = ? AND votes.type = ?",
p.id,
^vote_type
)
(如果有更好的方法来计算所有玩家的票数,那么我很高兴听到它。加入后,似乎没有票数的玩家不会被退回。 )
【问题讨论】:
-
fragment("SELECT count(*) FROM votes WHERE votes.player_id = ? AND (? IS NULL OR votes.type = ?)", p.id, ^vote_type, ^vote_type)怎么样?