2016-06-21 37 views
0
select x+y as z, 
case 
    when "x"+"y" < 0 then "Less Than Zero" 
    when "x"+"y" > 0 then "Non Zero" 
    else "Zero" 
end 
from sometable; 

返回預期結果,但多次添加每行數據。如何優化常見的子表達式?

我嘗試如下,但不工作,以優化查詢..

select x+y as z, 
case 
    when "z" < 0 then "Less Than Zero" 
    when "z" > 0 then "Non Zero" 
    else "Zero" 
end 
from sometable; 

始終返回「小於零」。

我在這個查詢上做錯了什麼?如何避免在執行查詢時多次添加AB

回答

0

SELECT子句中的列別名在同一SELECT子句中的其他表達式中不可用。 (應SELECT x AS y, y AS x ...發生什麼呢?)

可以做出這樣一個別名可通過移動它變成一個子查詢:

SELECT z, 
     CASE WHEN z < 0 THEN 'Less Than Zero' 
      WHEN z > 0 THEN 'Non Zero' 
      ELSE   'Zero' 
     END 
FROM (SELECT x + y AS z 
     FROM sometable); 

然而,這不僅節省了打字;它實際上並沒有優化掉重複計算:

 
sqlite> explain select z, z from (select x+y as z from sometable); 
addr opcode   p1 p2 p3 p4    p5 comment 
---- ------------- ---- ---- ---- ------------- -- ------------- 
0  Init   0  11 0     00 Start at 11 
1  OpenRead  1  2  0  2    00 root=2 iDb=0; sometable 
2  Rewind   1  9  0     00 
3  Column   1  0  3     00 r[3]=sometable.x 
4  Column   1  1  4     00 r[4]=sometable.y 
5  Add   4  3  1     00 r[1]=r[4]+r[3] 
6  Add   4  3  2     00 r[2]=r[4]+r[3] 
7  ResultRow  1  2  0     00 output=r[1..2] 
8  Next   1  3  0     01 
9  Close   1  0  0     00 
10 Halt   0  0  0     00 
11 Transaction 0  0  1  0    01 usesStmtJournal=0 
12 TableLock  0  2  0  sometable  00 iDb=0 root=2 write=0 
13 Goto   0  1  0     00