MySQL: using an alias in selected arithmetic - unknown field

Here is my choice:

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 

This is the bomb due to the next line where I add some aliases.

 (managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses 

Aliases are unknown fields.

Is there a way to save aliases for this arithmetic, or do I need to redo all the math that each alias generates to calculate totalExpenses? This seems like a very ugly way to do it.


UPDATE:

In your sentences, I now use a view.

 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; 
+4
source share
1 answer

Aliases are not available for reuse in the list of fields, for example:

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

You will have to wrap the choice with another, and then execute your math alias in this shell, for example.

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

Source: https://habr.com/ru/post/1498632/


All Articles