gpt4 book ai didi

MYSQL LEFT JOIN 3 个表包含 NULL 集

转载 作者:可可西里 更新时间:2023-11-01 07:36:04 26 4
gpt4 key购买 nike

试图对其他 SO 用户的问题/答案进行“逆向工程”,但没有成功。 JOINS 仍然让我望而却步。

我有三个表:race(所有比赛的列表)、result(每场比赛的结果)、driver(车手信息)。并非所有车手都参加过特定赛道的所有比赛。

比赛台

| 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 的简单规则?

谢谢!

最佳答案

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

关于MYSQL LEFT JOIN 3 个表包含 NULL 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com