I had the following query that doesn’t work and I was wondering how to fix it.
Player.select("players.*,
(SELECT COUNT(*) FROM Results
WHERE results.player_id = players.id and win = true)
as wins").where("wins > 0").order("wins desc")
I’m trying to limit parent Player records by a count of how many times its foreign key appears in the Results table when the boolean win is set to true. However, sometimes the foreign key will appear in the Results table but the boolean win field will be false resulting in a count of zero for records that I don’t want to see, so I thought I would try and eliminate these count of zero records using the .where(“wins > 0”) clause but I get this error:
PGError: ERROR: column “wins” does not exist
The funny thing is it finds the wins field when I try and order by it, but not with the added where clause.
I believe the following query will work:
This should Railsify thus, though naturally I haven’t tested it:
If you don’t care about rows where wins = 0, you can do an inner join instead of a left join, which might be faster.