我希望今天从我的数据库获取每个驱动程序的最后10个位置(authentication_id)。但是必须编写两个单独的查询,后者使用前者的结果集。我怎么能把它写成一个查询?
SELECT DISTINCT authentication_id FROM gps_trak WHERE DATE(location_timestamp) = DATE(NOW())
循环每个$ authID的结果集......
SELECT latitude, longitude FROM gps_trak WHERE authentication_id = ".$authID." ORDER BY location_timestamp DESC LIMIT 10";
有可能吗?
答案 0 :(得分:2)
您可以在查询中放置查询。这被称为' subquery'
SELECT latitude, longitude
FROM gps_trak
WHERE authentication_id
IN (
SELECT DISTINCT authentication_id
FROM gps_trak
WHERE DATE(location_timestamp) = DATE(NOW())
)
ORDER BY location_timestamp DESC LIMIT 10";
此外,您的问题也暗示了性能(优化)。如果这是一个问题,您可以尝试在您尝试过滤的列上放置索引(WHERE语句中使用的列)。有很多方法可以优化性能。这个(索引)和重写查询是提高性能的最佳方法。更多关于绩效的信息:http://www.infoworld.com/article/2616674/database-administration/10-essential-performance-tips-for-mysql.html
答案 1 :(得分:0)
尝试这样:
SELECT latitude, longitude FROM gps_trak WHERE authentication_id IN (
SELECT DISTINCT authentication_id FROM gps_trak
WHERE DATE(location_timestamp) = DATE(NOW())
) ORDER BY location_timestamp DESC LIMIT 10";
答案 2 :(得分:0)
这是一个相关的子查询版本(未经测试)......
SELECT DISTINCT x.authentication_id
FROM gps_trak x
JOIN
( SELECT latitude
, longitude
FROM gps_trak
WHERE authentication_id = x.authentication_id
ORDER
BY location_timestamp DESC LIMIT 10
) y
WHERE x.location_timestamp BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59');