优化代码以更快,更高效地运行

时间:2013-11-22 19:16:54

标签: mysql rows

我正在尝试找到一种方法来优化我的代码以更快地运行。我有很多select语句(大约30多个选择查询),然后我使用UNION ALL来连接所有这些select语句。我知道这是一种可怕的做法。我怎样才能改进它?如果您想查看结果,请点击以下链接:http://sqlfiddle.com/#!2/db3e7b/1

以下是我的代码示例:

SELECT 'east/flw' AS LOCATION, 
  ROUND(sum(CASE WHEN t2.locid = '2815' THEN t2.value ELSE 0 END), 2) AS Reading,
  ROUND(sum(CASE WHEN t2.locid = '2620' THEN t2.value ELSE 0 END), 2) AS Flw,
  ROUND(sum(CASE WHEN t2.locid = '2618' THEN t2.value ELSE 0 END), 2) AS Prs,
  ROUND(sum(CASE WHEN t2.locid = '2595' THEN t2.value ELSE 0 END), 2) AS Lvl

FROM table2 t2

INNER JOIN table1 t1
  ON t1.id = t2.locid
WHERE t2.t_stamp = (SELECT MAX(t2.t_stamp) 
                    FROM table2 t2 
                    WHERE t1.id = t2.locid)
GROUP BY 'east/flw'

UNION ALL

SELECT 'west/flw' AS LOCATION, 
  ROUND(sum(CASE WHEN t2.locid = '2715' THEN t2.value ELSE 0 END), 2) AS Reading,
  ROUND(sum(CASE WHEN t2.locid = '2720' THEN t2.value ELSE 0 END), 2) AS Flw,
  ROUND(sum(CASE WHEN t2.locid = '2718' THEN t2.value ELSE 0 END), 2) AS Prs,
  ROUND(sum(CASE WHEN t2.locid = '2795' THEN t2.value ELSE 0 END), 2) AS Lvl

FROM table2 t2

INNER JOIN table1 t1
  ON t1.id = t2.locid
WHERE t2.t_stamp = (SELECT MAX(t2.t_stamp) 
                FROM table2 t2 
                WHERE t1.id = t2.locid)

GROUP BY 'west/flw'
UNION ALL
.
.
.
UNION ALL
.
.
.

1 个答案:

答案 0 :(得分:0)

我会尝试抛弃所有UNION ALL并只读一次表,
这样:

SELECT 
  CASE 
         WHEN t2.locid IN ( '2815', '2620', '2618', '2595' )         
         THEN 'east/flw' 
         WHEN t2.locid IN ( '2715', '2720', '2718', '2795' )
         THEN 'west/flw'
         .......
         .......
         .......
         .......
  END AS LOCATION, 

  ROUND(sum(CASE WHEN t2.locid IN ( '2815', '2715', ............. ) 
                 THEN t2.value ELSE 0 END), 2) AS Reading,
  ROUND(sum(CASE WHEN t2.locid IN ('2620', '2720', ............... )
                 THEN t2.value ELSE 0 END), 2) AS Flw,
  ROUND(sum(CASE WHEN t2.locid IN ('2618', '2718', ...............)
                 THEN t2.value ELSE 0 END), 2) AS Prs,
  ROUND(sum(CASE WHEN t2.locid IN ('2595', '2795', ...............)
                 THEN t2.value ELSE 0 END), 2) AS Lvl
FROM table2 t2
INNER JOIN table1 t1
  ON t1.id = t2.locid
WHERE t2.t_stamp = (SELECT MAX(t2.t_stamp) 
                    FROM table2 t2 
                    WHERE t1.id = t2.locid)
GROUP BY location