MySQL子查询作为别名-未知列错误

时间:2018-08-18 11:22:31

标签: mysql

Column not found: 1054 Unknown column 'expensetot' in 'field list'

根据下面的查询,产生无错误的总计的最佳方法是什么?

SELECT 
  table1.cost,
  (SELECT SUM(expense) FROM table2 WHERE table2.key=table1.id) as expensetot
  (table1.cost+expensetot) as grandtotal,
  table3.label
FROM
  table1
  LEFT JOIN table3 ON table3.key=table1.id
WHERE
  table1.saledate>SUBDATE(CURDATE(), INTERVAL 1 YEAR)
ORDER BY grandtotal

2 个答案:

答案 0 :(得分:1)

您不能在select子句中使用别名,必须重复代码

您在table1.cost + ...之前错过了一个逗号。

,并且在subselect中,外部表不在范围内,因此您应该对子查询使用正确的连接以求和

 SELECT 
    table1.cost, 
    t.expensetot,
    table1.cost + t.expensetot as grandtotal,
    table3.label
FROM table1
INNER JOIN (
  select table2.key, sum(table2.expense) expensetot
  from table2
  group by  table2.key
) t on t..key=table1.id 
LEFT JOIN table3 ON table3.key=table1.id
  WHERE
    table1.saledate>SUBDATE(CURDATE(), INTERVAL 1 YEAR)
  ORDER BY grandtotal

答案 1 :(得分:0)

也许有帮助

      SELECT 
      table1.cost,
      (SELECT SUM(expense) FROM table2 WHERE table2.key=table1.id) as expensetot,
      (table1.cost+(SELECT SUM(expense) FROM table2 WHERE table2.key=table1.id)) as grandtotal,
      table3.label
    FROM
      table1
      LEFT JOIN table3 ON table3.key=table1.id
    WHERE
      table1.saledate>SUBDATE(CURDATE(), INTERVAL 1 YEAR)
    ORDER BY grandtotal

,或者您可以阅读有关查询中的用户变量的信息: https://dev.mysql.com/doc/refman/8.0/en/user-variables.html