简体   繁体   English

带有子选择的MySQL查询花费的时间太长。

[英]Mysql query with sub-selects taking too long..

Every 5 minutes my historical table is updated (by another process) with a new record (TAG_NAME remains the same but TIME and VALUE are updated). 我的历史记录表每隔5分钟就会通过新记录更新(通过另一个过程)(TAG_NAME保持不变,但TIME和VALUE被更新)。 I am using the following query to return the LATEST record while also grouping by TAG_NAME. 我正在使用以下查询返回LATEST记录,同时也按TAG_NAME进行分组。

SELECT 
TAG_NAME,max(TIME) as max_time, 
(select value from historical where TAG_NAME=hist.TAG_NAME order by time desc limit 1) as max_value 
FROM historical hist 
WHERE TIME IS NOT NULL AND GROUP BY TAG_NAME;

This query is taking as long as 1 minute on a table with 100k rows. 在具有10万行的表上,此查询最多需要1分钟。 Can anyone help me optimize this query? 谁能帮助我优化此查询?

Much Thanks! 非常感谢!

Try this: 尝试这个:

SELECT 
TAG_NAME, max(`TIME`) as max_time, max(`value`) as max_value
FROM historical
WHERE `TIME` IS NOT NULL 
GROUP BY TAG_NAME
;

You could get the combined maximum, so if two times are the same you get the biggest value. 您可以获得合并的最大值,因此,如果两次相同,则将获得最大价值。

select TAG_NAME, max(concat(time,value)) as time_value
from historical 
group by TAG_NAME

If necessary you can split time and value in mySQL, but you can also split it in the app. 如有必要,您可以在mySQL中拆分时间和值,但也可以在应用程序中拆分它。

http://sqlfiddle.com/#!9/6d210/1 http://sqlfiddle.com/#!9/6d210/1

SELECT 
h.*
FROM historical h
LEFT JOIN historical h1
ON h.TAG_NAME = h1.TAG_NAME
  AND h.time<h1.time
WHERE h1.time IS NULL

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

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