我有以下查询无效,我想知道如何修复它。
Player.select("players.*,
(SELECT COUNT(*) FROM Results
WHERE results.player_id = players.id and win = true)
as wins").where("wins > 0").order("wins desc")
我正在尝试将父级Player记录限制为当布尔值win
设置为true时其外键出现在Results表中的次数。但是,有时外键会出现在Results表中,但布尔win
字段将为false,导致我不想看到的记录数为零,所以我想我会尝试消除这些使用.where(“wins> 0”)子句计算零记录,但是我收到此错误:
PGError:ERROR:列“wins”不存在
有趣的是,当我尝试按顺序排序时,它会找到wins
字段,但不会添加where子句。
答案 0 :(得分:1)
我相信以下查询可行:
select players.*, count(results.id) as wins from players left join results on results.player_id = players.id and results.win = true group by players.id having count(results.id) > 0 order by wins desc;
这应该是Railsify,尽管我自然没有测试过它:
Player.select('players.*, count(results.id) as wins').joins('left join results on results.player_id = players.id and results.win = true').group('players.id').having('count(results.id) > 0').order('wins desc')
如果你不关心wins = 0的行,你可以做一个内连接而不是左连接,这可能会更快。