简体   繁体   English

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

[英]MySQL: How can I select a value (date) based on a result from another table and include it in said result?

I have the following MySQL tables (Simplified) 我有以下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

I want to be able to list all drivers with their numRaces, firstRace, lastRace, bestRound, bestAverageRound and the dates on which their bestRound and bestAverageRound happened. 我希望能够列出所有驱动程序及其numRaces,firstRace,lastRace,bestRound,bestAverageRound以及其bestRound和bestAverageRound发生的日期。 I'm having problems with the last two, the dates for bestRound and bestAverageRound. 我对最后两个日期,bestRound和bestAverageRound的日期有疑问。

This is what I have so far: 这是我到目前为止的内容:

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

This is working correctly. 这工作正常。 But how do I proceed to select the dates from the RACE table on which the bestRound and bestAverageRound occurred? 但是,如何继续从RACE表中选择发生bestRound和bestAverageRound的日期呢? Thanks for your time. 谢谢你的时间。

Try this solution: 试试这个解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM