未知列错误

rdlzhqv9  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(349)
Column not found: 1054 Unknown column 'expensetot' in 'field list'

根据下面的查询,生成grandtotal而不出错的最佳方法是什么?

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
5vf7fwbs

5vf7fwbs1#

不能在select子句中使用别名,必须重复代码
你在table1.cost+之前漏掉了一个逗号。。。
在subselect中,外部表不在范围内,因此应该使用适当的join with subquery for sum

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
os8fio9y

os8fio9y2#

也许这会有帮助

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

相关问题