I have the following 3 tables:
mysql> explain runners;
+-------------+------------------+
| Field | Type |
+-------------+------------------+
| runner_id | int(10) unsigned |
| name | varchar(100) |
+-------------+------------------+
mysql> explain runs;
+-------------+------------------+
| Field | Type |
+-------------+------------------+
| run_id | int(10) unsigned |
| runner_id | int(10) unsigned |
| race_id | int(10) unsigned |
| position | int(10) |
+-------------+------------------+
mysql> explain races;
+-------------+------------------+
| Field | Type |
+-------------+------------------+
| race_id | int(10) unsigned |
| date | datetime |
+-------------+------------------+
Next, I have to display all the races a given runner participated in, something like this:
mysql> select runner.name, runs.run_id, runs.position, races.race_id
from runners
join runs on(runs.runner_id = runners.runner_id)
join races on(races.race_id = run.run_id)
where runners.runner_id = 1;
+------------------+--------+----------+---------+
| name | run_id | position | race_id |
+------------------+--------+----------+---------+
| John Runner | 1 | 1 | 1 |
| John Runner | 7 | 3 | 2 |
| John Runner | 15 | 2 | 3 |
................... more lines ...................
+------------------+--------+----------+---------+
Now I should add another column called “win/second” to this query, that will display the name of the runnner that finished second if the current runner’s position = 1 or display the name of the winning runner in that race if the current runner’s position != 1, but I just don’t know how to get this working or even what to start with.
This should get you what you need:
And the SQL Fiddle.
Good luck.