通过查询

时间:2016-01-27 14:29:11

标签: php mysql max

我有一张飞行表,正努力确定每架飞机的最后一个城市#降落在哪里。

错误的查询是:

SELECT DISTINCT `flight_nmbr`, COUNT(record_id) AS Flights,
MIN(`depart_date_time`) AS `first_flight`,
MAX(`depart_date_time`) AS `last_flight`,
MAX(`location`) AS `current_location`
FROM history 
GROUP BY `flight_nmbr`
HAVING records > 1
ORDER BY MAX(`depart_date_time`) DESC;

此声明将表明最后一班航班(目前位于飞机上)是Winston-Salem或Zanesville(即MAX城市名称)。

我需要最后一个位置(MAX(depart_date_time)的位置),最后/最近的航班,即亚特兰大和休斯顿。

Microsoft Access有一个查询的最后一个函数,但我们正在使用MySQL和PHP从Access迁移。

有人可以帮助调整此查询吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您可以将子串与GROUP_CONCAT技巧

一起使用
SELECT DISTINCT flight_nmbr,
 COUNT(record_id) AS Flights,
MIN(depart_date_time) AS first_flight,
MAX(depart_date_time) AS last_flight,
SUBSTRING_INDEX(GROUP_CONCAT(location ORDER BY depart_date_time DESC),',',1) AS current_location
FROM history 
GROUP BY flight_nmbr
HAVING records > 1
ORDER BY MAX(depart_date_time) DESC;