简体   繁体   English

如何使此查询更有效?

[英]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". 我之前的问题的评论说:“我也建议您在此处查看答案: stackoverflow.com/questions/1313120/… 。您接受的答案在技术上是正确的,实际上,结果可能效率很低,因为MySQL不喜欢相关子查询”。

The SQl of the answer which I accepted is at SQL fiddle . 我接受的答案的SQl 在SQL小提琴上 The referenced question compares LEFT JOIN and INNER JOIN. 所引用的问题比较“左联接”和“内联接”。 The SQL Fddle uses only JOIN< which I understand to default to INNER JOIN. SQL Fddle仅使用JOIN <,据我理解默认为INNER JOIN。

So, how can I rewrite the query to use a LFT JOIN? 因此,如何重写查询以使用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. 我不确定mysql的性能,但是您可以将LEFT JOIN用于将取消您的位置资格的行,然后使用WHERE仅选择LEFT JOIN不匹配的记录。

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 或者,在SQLFiddle中: http ://sqlfiddle.com/#!2/2e994/31/0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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