0

我有以下查询不起作用,我想知道如何解决它。

Player.select("players.*, 
    (SELECT COUNT(*) FROM Results 
    WHERE results.player_id = players.id and win = true) 
as wins").where("wins > 0").order("wins desc")

win当布尔值设置为true时,我试图通过计算其外键出现在结果表中的次数来限制父播放器记录。但是,有时外键会出现在结果表中,但布尔win字段会是错误的,导致我不想看到的记录计数为零,所以我想我会尝试使用消除这些零记录计数.where("wins > 0") 子句,但我收到此错误:

PGError:错误:列“wins”不存在

有趣的是,wins当我尝试按它进行排序时,它会找到该字段,但不会在添加的 where 子句中找到。

4

1 回答 1

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 的行,则可以进行内连接而不是左连接,这可能会更快。

于 2012-06-19T18:08:05.840 回答