I'm working on a political application for a client, and I've got two database tables. One has all the registered voters in a certain city, and the other has all the votes for each registered voter. Combined, these two tables number well over 7 million records. This site is coded on CakePHP.
I'm already narrowing the results by a number of criteria, but I need to filter it also based on the percentage of elections that a given voter has voted in since they registered. I have all the votes, the year they registered, and that there are 3 elections every 4 years. I've tried doing a subquery to filter the results, but it took far too long. It took 10 minutes to return 10 records. I have to do this in a join some way, but I'm not at all versed in joins.
This is basically what I need to do:
SELECT * FROM voters
WHERE (number of votes voter has) >= (((year(now())-(registration_year) ) * 3/4)
* (percentage needed))
All of that is pretty straight-forward. The trick is counting the votes the voter has from the votes database. Any ideas?