试图“反向工程”其他SO用户问题/答案我的问题但不能。 JOINS仍然没有找到我。
我有三个表:种族(所有种族的列表),结果(每个种族的结果),驱动程序(驱动程序信息)。并非所有车手都参加了特定赛道的所有比赛。
比赛表
| race_id | track_id | year | complete |
+-----------+------------+--------+----------+
| 1 | 1 | 2006 | 1 |
| ... | ... | ... | ... |
| 21 | 1 | 2007 | 1 |
| ... | ... | ... | ... |
| 135 | 1 | 2008 | 1 |
| ... | ... | ... | ... |
| 215 | 1 | 2009 | 1 |
| ... | ... | ... | ... |
| 292 | 1 | 2010 | 1 |
| ... | ... | ... |... |
| 351 | 1 | 2011 | 0 |
+-----------+------------+--------+----------+
结果表
| race_id | driver_id | finish |
+---------+-----------+--------+
| 135 | 1 | 15 |
| ... | ... | ... |
| 292 | 1 | 6 |
+---------+-----------+--------+
驱动程序表
| driver_id | name |
+-----------+------------+
| 1 | Joe Driver |
+-----------+------------+
我想要一个显示的结果集:
| name | race_id | year | finish |
+------------+---------+--------+--------+
| Joe Driver | 21 | 2007 | NULL |
| Joe Driver | 135 | 2008 | 15 |
| Joe Driver | 215 | 2009 | NULL |
| Joe Driver | 292 | 2010 | 6 |
+------------+---------+--------+--------+
Joe Driver仅参加了2006年之后在track_id = 1的4场比赛中的2场比赛,仅包括完成的比赛(1)
这是我目前的查询:
SELECT driver.driver, race.id, race.year, result.finish
FROM race
LEFT JOIN result ON race.id = result.race_id
LEFT JOIN driver ON result.driver_id = driver.driver_id
WHERE race.track_id = 1
AND race.year > 2006
AND race.complete = 1
AND driver.driver_id = 1
ORDER BY race.id ASC
我得到的结果只显示了司机所在的比赛:
| name | race_id | year | finish |
+------------+---------+--------+--------+
| Joe Driver | 135 | 2008 | 15 |
| Joe Driver | 292 | 2010 | 6 |
+------------+---------+--------+--------+
我确定我忽略了加入JOINS的简单规则?
谢谢!
答案 0 :(得分:3)
SELECT driver.driver, race.id, race.year, result.finish
FROM race
CROSS JOIN
driver
LEFT JOIN
result
ON result.race_id = race.id
AND result.driver_id = driver.driver_id
WHERE race.track_id = 1
AND race.year > 2006
AND race.complete = 1
AND driver.driver_id = 1
ORDER BY
race.id ASC