MySQL:如何根据另一个表的结果选择一个值(日期)并将其包含在所述结果中?

时间:2012-07-22 09:22:39

标签: mysql sql

我有以下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

这是正常的。但是,如何从最佳响应和bestAverageRound发生的RACE表中选择日期?谢谢你的时间。

1 个答案:

答案 0 :(得分: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