简体   繁体   English

使用MAX(id)优化查询

[英]Optimize query with MAX (id)

I have this query that shows me the last id by id_units , depending on the date. 我有此查询,根据日期显示了id_units的最后一个id

My query is: 我的查询是:

SELECT max(swg.id) AS id
 FROM swg
 WHERE swg.status != 0
 AND sg.dateswg <= TIMESTAMPADD(DAY,(6-WEEKDAY('2015-12-28')),'2015-12-28')
 GROUP BY swg.id_units
ORDER BY swg.id;

The query returns more than 2000 records, I think that there is a way that I can performance this query. 该查询返回了2000多个记录,我认为有一种方法可以执行此查询。

I am trying to performance my query like this: 我正在尝试执行这样的查询:

SELECT id
FROM (SELECT * FROM swg WHERE status != 0 AND dateswg <= TIMESTAMPADD(DAY,(6-WEEKDAY('2015-12-28')),'2015-12-28') ORDER BY id_units, id desc) x
GROUP BY id_units;

It is works, but I would like to know if there is another way to improve it 这是可行的,但是我想知道是否还有另一种方法可以改善它

Regard! 看待!

This is your query: 这是您的查询:

SELECT max(swg.id) AS id
FROM swg
WHERE swg.status <> 0 AND
      swg.dateswg <= TIMESTAMPADD(DAY, 6 - WEEKDAY('2015-12-28'), '2015-12-28')
GROUP BY swg.id_units
ORDER BY MAX(swg.id);

This is tricky to optimize, because an index cannot be used for both conditions. 优化起来很棘手,因为索引不能同时用于两种情况。 You can start with a composite index on all four columns used in the query: swg(dateswg, status, id_units, id) 您可以从查询中使用的所有四个列上的复合索引开始: swg(dateswg, status, id_units, id)

Of status is only either 0 or 1 , then change to status = 1 so that the Optimizer has one place to look, not two disjoint places. status值为01 ,然后更改为status = 1这样Optimizer会看到一个位置,而不是两个不相连的位置。 Then have 然后有

INDEX(status, dateswg, id_units, id) -- in this order.

That will be pretty good for the WHERE and will be "covering". 对于WHERE ,这将是相当不错的,并且将“覆盖”。

Unfortunately both the GROUP BY and the ORDER BY will need a sort; 不幸的是, GROUP BYORDER BY都需要排序; the latter one will be 2000 rows, and probably be done in RAM; 后者将是2000行,可能在RAM中完成; I can't tell about the former. 我不能说前者。

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

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