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が発生した日付を含むすべてのドライバーを一覧表示できるようにしたいと思います。最後の2つ、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

これは正しく機能しています。しかし、bestRoundとbestAverageRoundが発生したRACEテーブルから日付を選択するにはどうすればよいですか?御時間ありがとうございます。

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 に答える