0

我有以下 MySQL 表(简体)

DRIVER (D)
----------
id (PK)
name

RACE (RA)
---------
id (PK)
date

RESULT (RE)
-----------
id (PK)
raceid (FK -> RACE.id)
driverid (FK -> DRIVER.id)
bestRound
averageRound

我希望能够列出所有车手及其 numRaces、firstRace、lastRace、bestRound、bestAverageRound 以及他们的 bestRound 和 bestAverageRound 发生的日期。我在最后两个问题上遇到问题,即 bestRound 和 bestAverageRound 的日期。

这是我到目前为止所拥有的:

SELECT D.name, COUNT(DISTINCT RE.raceid) AS numRaces, min(RA.date) AS firstRace,
max(RA.date) AS lastRace, min(RE.bestRound) AS bestRound,
min(RE.averageRound) AS bestAverageRound 
FROM DRIVER D
JOIN RESULT RE ON RE.driverid = D.id
JOIN RACE RA ON RA.id = RE.raceid
GROUP BY D.id
ORDER BY D.name

这工作正常。但是我如何继续从 RACE 表中选择 bestRound 和 bestAverageRound 发生的日期?谢谢你的时间。

4

1 回答 1

0

试试这个解决方案:

SELECT 
    a.*, b.date AS bestRoundDate, c.date AS bestAverageRoundDate
FROM
(
    SELECT 
        d.id, 
        d.name,
        COUNT(DISTINCT re.raceid) AS numRaces,
        MIN(ra.date) AS firstRace,
        MAX(ra.date) AS lastRace,
        MIN(re.bestRound) AS bestRound,
        MIN(re.averageRound) AS bestAverageRound
    FROM driver d
    INNER JOIN result re ON d.id = re.driverid
    INNER JOIN race ra ON re.raceid = ra.id
    GROUP BY d.id, d.name
) a
INNER JOIN
(
    SELECT aa.driverid, aa.bestRound, bb.date
    FROM result aa
    INNER JOIN race bb ON aa.raceid = bb.id
) b ON a.id = b.driverid AND a.bestRound = b.bestRound
INNER JOIN
(
    SELECT aa.driverid, aa.bestAverageRound, bb.date
    FROM result aa
    INNER JOIN race bb ON aa.raceid = bb.id
) c ON a.id = c.driverid AND a.bestAverageRound = c.bestAverageRound
ORDER BY
    a.name
于 2012-07-22T10:04:38.640 回答