One segment of the Horse Racing Information System I worked on in college involved finding horses from a given race that had raced against each other.
This is the more general example where I have a given horse and wish to find all the horses they have run against:
SELECT h2.horsename FROM horse h1 JOIN raceentrants r1 ON h1.horseid = r1.horseID JOIN raceentrants r2 ON r1.raceID = r2.raceID JOIN horse h2 ON h2.horseid = r2.horseID WHERE r1.horseID =1 AND h2.horsename NOT IN ( 'Horse A' );
My representation of the steps involved are:
- Select the correct horse from the Horse table
- Join this to the RaceEntrants table on horseId to find all the horse's races
- Join this to the RaceEntrants table on raceId to find all other entrants in these races
- Join this to the Horse table to find the other horses
- Make sure we do not return the original horse
If I really wantd just the names I could have used 'distinct' but it is more likely that in a ful database you would be returning on all horse-race combinations.
This is quite cumbersome but it gets worse ...