1

I'm looking to get todays last 10 locations from my database for each driver (authentication_id). But have had to write two separate queries, the latter using the resultset of the former. How could I write it as a single query?

SELECT DISTINCT authentication_id FROM gps_trak WHERE DATE(location_timestamp) = DATE(NOW())

loop the resultset for each $authID...

SELECT latitude, longitude FROM gps_trak WHERE authentication_id = ".$authID." ORDER BY location_timestamp DESC LIMIT 10";

Is it possible?

3 Answers 3

2

You can put a query inside a query. This is called a 'subquery'

example

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";

Performance optimization

Also your question also hinted about performance (optimization). If this is a problem you could try puting indexes on the columns you try to filter (columns used in WHERE statements). There are alot of ways you can optimize performance. This one (indexes), and rewriting your queries are the best way to increase performance. More on performance: http://www.infoworld.com/article/2616674/database-administration/10-essential-performance-tips-for-mysql.html

Sign up to request clarification or add additional context in comments.

Comments

0

try like this:

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";

Comments

0

Here's a correlated subquery version (untested)...

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.