2013-08-27 93 views
2

其實我的查詢是這樣的:可以指望MySQL的別名結果

SELECT ABS(20-80) columnA , ABS(10-70) columnB , 
ABS(30-70) columnC , ABS(40-70) columnD , etc.. 

的PB是每ABS()實際上是在一些複雜的計算,我需要添加一個最後columnTotal女巫是每個ABS()的總和,我想以一種方式做到這一點,無需重新計算所有。我想達到的是:

SELECT ABS(20-80) columnA , ABS(10-70) columnB , 
ABS(30-70) columnC , ABS(40-70) columnD , SUM(columnA+columnB+columnC+columnD) columnTotal 

。結果預計這個樣子的:

columnA columnB columnC columnD columnTotal 
    60   60   40   30   190 

不知道其可能

回答

2

是,在MySQL你可以這樣做:

SELECT 
    @a:=ABS(40-90) AS column1, 
    @b:=ABS(50-10) AS column2, 
    @c:=ABS(100-40) AS column3, 
    @[email protected][email protected] as columnTotal; 
 
+---------+---------+---------+-------------+ 
| column1 | column2 | column3 | columnTotal | 
+---------+---------+---------+-------------+ 
|  50 |  40 |  60 |   150 | 
+---------+---------+---------+-------------+ 
1 row in set (0.00 sec) 
+0

千恩萬謝,可以完美運行! – albator

0

您可以在一個更層包裹這樣的:

select columnA, columnnB, columnnC, columnnD, (columnA+ columnnB+ columnnC+ columnnD) total 
from 
(
SELECT ABS(20-80) columnA , ABS(10-70) columnB , 
ABS(30-70) columnC , ABS(40-70) columnD , etc.. 
) 
0
SELECT t.*, (columnA+columnB...) as total 
FROM (
    SELECT ABS(20-80) columnA , ABS(10-70) columnB, ABS(30-70) columnC , ABS(40-70) columnD 
    ... 
) as t 
0

使用派生表:

SELECT 
    columnA , columnB , 
    columnC , columnD , 
    SUM(columnA+columnB+columnC+columnD) columnTotal 
FROM 
(
    SELECT 
     ABS(20-80) columnA , ABS(10-70) columnB , 
     ABS(30-70) columnC , ABS(40-70) columnD 
    FROM ... 
) AS dt