I have a database full of sports results. I'd like to select some results based on some characteristics of the previous results. Here's the database structure:
CREATE TABLE `results` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`date` DATETIME NOT NULL ,
`home_score` INT NOT NULL ,
`away_score` INT NOT NULL ,
`home_team_id` INT NOT NULL ,
`away_team_id` INT NOT NULL
);
So I'd like to do queries like "find results where a team has won their two previous home games" - i.e. for a specific home_team_id order by by date, then select each row where in the previous two rows home_score > away_score.
I know this is a bit complicated so any pointers as to how to solve this will be massively appreciated. I currently have a version in PHP (selects all rows and then performs this type of query) but performance is very slow and it uses a huge amount of memory (there are over 20,000 rows in the database).
EDIT: Thanks for a couple of neat answers. Ideally, though, I'd like to be able to run queries on all columns, not just looking at W, D or L. A more complicated example would be "find all results where the home team had won each of their five previous home games by at least two goals and the away team had lost each of their away games by at least one goal."