如何只用一个查询执行这个php循环和多个mysql查询?

时间:2016-06-19 19:20:43

标签: mysql

我有一个查询,该查询获得了比赛中跑步者开始比赛时间的最早日期:

SELECT
    MIN(races.eventdate)
FROM
    races,
    runners
WHERE
    races.id=runners.raceid AND runners.time_hsecs IS NOT NULL

races表有一个种族列表,以及它们所在的轨道。 runners表包含每个种族及其时间的跑步者。

上面的查询获取记录完成时间的最早日期。但是,如果我想获得每个曲目名称的最早日期呢?凭借我有限的经验,我将创建一个循环,遍历每个曲目名称,然后执行上面相同的查询,但仅隔离到每个曲目,例如(伪代码)

foreach($trackname_array as $some_name) {

    SELECT
        MIN(races.eventdate)
    FROM
        races,
        runners
    WHERE
        races.id=runners.raceid AND runners.time_hsecs IS NOT NULL
    AND
        races.trackname=$some_name

    // returns earliest eventdate that matches the query for trackname

}

但我想了解这样的事情是如何完全在sql中完成的?

2 个答案:

答案 0 :(得分:0)

您似乎在寻找GROUP BY语法:

SELECT
    MIN(races.eventdate) as eventDate, races.id AS raceId,races.trackname
 FROM
    races,
    runners
WHERE
    races.id=runners.raceid AND runners.time_hsecs IS NOT NULL
GROUP BY races.id, races.trackName

答案 1 :(得分:0)

SELECT
    MIN(races.eventdate) as eventDate,races.trackname
 FROM
    races,
    runners
WHERE
    races.id=runners.raceid AND runners.time_hsecs IS NOT NULL
GROUP BY  races.trackName, date(races.eventdate)

如果我理解正确