简体   繁体   中英

How to make this query more efficient?

A comment to my previous question said "I would suggest looking at the answers here as well: stackoverflow.com/questions/1313120/… . The answer you accepted thought technically correct, in practice might turn out very inefficient, since MySQL does not like correlated subqueries".

The SQl of the answer which I accepted is at SQL fiddle . The referenced question compares LEFT JOIN and INNER JOIN. The SQL Fddle uses only JOIN< which I understand to default to INNER JOIN.

So, how can I rewrite the query to use a LFT JOIN?

I'm not certain of the performance on mysql, but you can LEFT JOIN for rows that would disqualify your position, and then use WHERE to only select records where the LEFT JOIN didn't match.

SELECT v.id
     , v.description
     , v.type
     , p.time_stamp
     , p.latitude
     , p.longitude
  FROM positions p
  JOIN vehicles v ON v.id = p.id
  LEFT JOIN positions l ON l.id = p.id 
                        AND l.time_stamp > p.time_stamp
  WHERE l.id IS NULL

Or, in SQLFiddle: http://sqlfiddle.com/#!2/2e994/31/0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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