简体   繁体   English

重写MySQL子查询作为联接

[英]Rewriting MySQL subquery to be a join

I have a table with a lot of rows, and it's very inefficient to do subqueries on. 我的表有很多行,执行子查询的效率很低。 I can't wrap my head around how to do a join on the data to save time. 为了节省时间,我无法全神贯注于如何对数据进行联接。

Here is what I have: http://sqlfiddle.com/#!2/6ab0c/3/0 这是我所拥有的: http : //sqlfiddle.com/#!2/6ab0c/3/0

This is a bit long for a comment. 这有一段评论的时间。

First, I think you are missing an ORDER BY in the subquery. 首先,我认为您在子查询中缺少ORDER BY I suspect you want order by I2.date to get the "next" row. 我怀疑您想order by I2.date以获取“下一个”行。

Second, MySQL doesn't quite offer the functionality you need. 其次,MySQL并未完全提供您需要的功能。 You could rewrite the query using variables. 您可以使用变量重写查询。 But, because you don't describe what it is doing, it is hard to be sure that a rewrite would be correct. 但是,由于您没有描述它在做什么,因此很难确保重写是正确的。 That is one way to speed the query. 这是加快查询速度的一种方法。

Third, this query would be much faster -- and probably fast enough -- with an index on items(location, sku, date) . 第三,此查询使用items(location, sku, date)的索引会更快,并且可能足够快。 That index is probably all you need. 该索引可能就是您所需要的。

SELECT I1.*, MIN(I2.exit_date)
FROM Items I1

LEFT JOIN (
  SELECT date as exit_date, location, sku 
  FROM Items
  ORDER BY date asc
) as I2
ON I2.exit_date > I1.date
  AND I2.location = I1.location
  AND I2.sku = I1.sku 
GROUP BY I1.id

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

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