MySQL:在选择算术中使用别名 - 未知字段

时间:2013-08-23 15:09:50

标签: mysql sql

这是我的选择:

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?这似乎是一种非常难看的方式。


更新:

根据您的建议,我现在使用派生表。

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;

1 个答案:

答案 0 :(得分:4)

别名不能在字段列表中重复使用,例如:

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

您必须将select包装为另一个,然后在该包装中进行别名数学运算,例如

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