修改查询以更快地执行但仍然获得相同的结果

时间:2014-04-02 18:54:50

标签: mysql optimization row

我在这里有这个查询,应该像这样输出我的数据:

  tstamp             |   a1    |   a2
2014-03-29 01:00:00  | 100.12  | 150.00
2014-03-29 01:15:00  | 104.12  | 350.00
2014-03-30 04:00:00  | 500.12  | 750.00
2014-03-31 04:15:00  | 504.12  | 700.00

这是我使用的查询:

select distinct t_stamp, 
(select value from table1 as table2 where path='a1' and table2.t_stamp=table1.t_stamp) as a1,
(select value from table1 as table2 where path='a2' and table2.t_stamp=table1.t_stamp) as a2
from table1
WHERE date(t_stamp) between = "2014-03-29" and "2014-03-30"

我所拥有的问题是在我的真实数据库中,每条路径至少有5-8k行数,这个查询运行时间太长,太久我无法查看是否我得到的价值是否正确。 我以为我可以使用这个原因我首先在sqlfiddle上测试它并获得了我需要的结果但是当我在我的真实数据库上试用它时 它太长了。

有没有办法可以修改这个查询并获得相同的结果,但只是让它执行得更快?

同样在我的数据库中,时间戳是unixcode,即使我想(不允许),也不能以可读格式编辑它。

这是我使用的sqlfiddle:http://sqlfiddle.com/#!2/889ff/1

1 个答案:

答案 0 :(得分:0)

如果速度更快,请告诉我。FIDDLE

SELECT 
    DISTINCT t_stamp AS time_stamp,
    val_1, 
    val_2
FROM table1
LEFT JOIN (
  SELECT
    t_stamp AS t1_stamp,
    value AS val_1
  FROM table1 AS table2
  WHERE path='a1'
) AS a1 on a1.t1_stamp = t_stamp
LEFT JOIN (
  SELECT
    t_stamp AS t2_stamp,
    value AS val_2
  FROM table1 AS table2
  WHERE path='a2'
) AS a2 on a2.t2_stamp = t_stamp
WHERE date(t_stamp) = "2014-03-29"