1
我試圖找到一種方法來優化代碼以加快運行速度。我有很多選擇語句(大約30多個選擇查詢),然後我使用UNION ALL
來連接所有這些選擇語句。我知道這是一個可怕的方式。我該如何改進它?這裏的鏈接,如果你想看到的結果: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
.
.
.
表格說明??解釋命令?索引? PK和FK? – jcho360
該表位於提供的鏈接中。並且我無法對我的實際數據庫上的表進行任何更改 – sleepsleepsleep90731
如果無法修改表格,我不會在sqlfiddle中查看任何PK,FK,UK,index,etx,您希望如何加快速度一個簡單的查詢? – jcho360