2013-08-23 56 views
4

這是我的選擇:MySQL的:在選擇算法使用別名 - 未知領域

SELECT 
    SUM(t.amount + c.designFeeValue) as cashReceived, 
    ROUND(SUM(i.value) * (m.percentOurs/100)) as adValue, 
    m.managementFee as managementFee, 
    m.productionCost as productionCost, 
    5 as emailAddress, 
    (
    (
     SELECT value 
     FROM commission_transactions 
     WHERE isDebit IS 
     TRUE 
    ) - 
    (
     SELECT value 
     FROM commission_transactions 
     WHERE isDebit IS 
     FALSE 
    ) 
) as miscExpenses, 
    (managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses 

這是因爲以下行,其中我添加了一些別名的轟炸。

(managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses 

別名是未知字段。

有沒有一種方法可以保留這個算術的別名,還是我需要重新做所有的計算totalExpenses每個別名的數學?這似乎是一個非常醜陋的做法。


UPDATE:

根據您的建議,我現在用的是派生表。

SELECT 
    cashReceived, 
    adValue, 
    managementFee, 
    productionCost, 
    emailAddress, 
    miscExpenses, 
    adValue + managementFee + productionCost + emailAddress + miscExpenses as totalExpenses 
FROM (
    SELECT 
    SUM(t.amount + c.designFeeValue) as cashReceived, 
    ROUND(SUM(i.value) * (m.percentOurs/100)) as adValue, 
    m.managementFee as managementFee, 
    m.productionCost as productionCost, 
    5 as emailAddress, 
    (
     (
     SELECT value 
     FROM commission_transactions 
     WHERE isDebit IS TRUE 
    ) - 
     (
     SELECT value 
     FROM commission_transactions 
     WHERE isDebit IS FALSE 
    ) 
    ) as miscExpenses 
    FROM magazines m 
    JOIN insertions i ON i.magazineId = m.id 
    JOIN transactions t ON t.insertionId = i.id 
    JOIN contracts c ON i.contractId = c.id 
    JOIN commission_transactions ct ON m.id = ct.magazineId 
    WHERE m.id = 17 
    AND t.isChargedBack IS FALSE 
    AND t.`timestamp` >= '2013-08-01 00:00:00' 
    AND t.`timestamp` < '2013-09-01 00:00:00' 
    AND ct.createdDate >= '2013-08-01 00:00:00' 
    AND ct.createdDate < '2013-09-01 00:00:00' 
) sub; 
+0

嘗試寫出yourTablesAlias.yourColumnAlias,如果不起作用,請重新計算。 like'miscexpenses.managementFree + miscExpenses.productionCost' – Scotch

回答

4

別名不可用於字段列表中的再利用,如:

mysql> select 5 as five, five + 1 as six; 
ERROR 1054 (42S22): Unknown column 'five' in 'field list' 

你必須包裹選擇用另一個,然後做你的別名數學在包裝,例如

select *, managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses 
FROM (
    ... your above query here ... 
) 
+0

遇到語法問題,請參閱我更新的問題 – Lurk21

+0

此分號:''2013-09-01 00:00:00';'在各個日期結束時不應該是那裏。 ';'是一個語句終結符,但是你還沒有完成你的查詢,至少留下了一個'('open and dangling。 –

+0

哦,真是啊!謝謝! – Lurk21