获取与每行参数相关的最大值和最小值的速度很慢
我需要获取某些跟踪数据,包括几个最大值和分钟。我已经有一个可怕的方法来做到这一点,但如你所知,这真的很慢,因为我正在使用子查询,并且表有几千行。具体来说,我需要根据当前行的 type_dev 获得每行不同的 MAX 值。当有 24000 条记录时,它变得不可用,而且当我尝试使用 MAX 子句时,我认为速度会更慢。
SELECT dt.some_data, dt.date_visit, dt.url,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev ORDER BY date_visit DESC LIMIT 1) last_visit,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev and url = dt.url ORDER BY date_visit DESC LIMIT 1) last_visit_to_this_url
FROM device_tracker dt WHERE some_where_clauses;
请注意,我不需要全局最大值(这可能非常简单),但例如在这种情况下,我得到每个 type_dev 的最大日期(每行可以是不同的类型,也可以不是)关于每一行的某个 url 的最大日期。
我需要同样的最小日期。
当然有很多更好的方法可以做到这一点。有人能解释一下吗?
I need to get certain tracked data, including a couple of max and mins. I already have a horrible way to do it below, but as you know this is REALLY slow because i'm using subqueries and the table has a couple of thousands of rows. Specifically I need to get a different MAX values per row, depending on the type_dev of the current row. with 24000 records it becomes unusable, and I think is even slower when I try with MAX clauses instead.
SELECT dt.some_data, dt.date_visit, dt.url,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev ORDER BY date_visit DESC LIMIT 1) last_visit,
(SELECT date_visit FROM device_tracker
WHERE type_dev = dt.type_dev and url = dt.url ORDER BY date_visit DESC LIMIT 1) last_visit_to_this_url
FROM device_tracker dt WHERE some_where_clauses;
Please note that I don't need global max values (it could be really easy), but for example in this case I'm getting the max date of every single type_dev (every row can be a different type or not) and also the max date of a certain url regarding each row.
I Need the same with the minimun dates.
For sure there are a lot of nicer ways to do it. Could anyone throw some light on it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
(type_dev, url, date_visit)
上创建一个复合索引,以便快速工作。Create a composite index on
(type_dev, url, date_visit)
for this to work fast.