为什么mySql不识别表字段列表中的列?

问题描述 投票:2回答:2

为什么mySql在表字段列表中抛出错误“#1054 - 未知列'this.revenue'”?请参阅下面的数据库表结构和SQL语句的附图。 enter image description here

通过这个问题,我试图将去年的收入与今年的收入进行比较。

SELECT this.revenue as current_amount , 
this.weekno, 
history.revenue AS past_amount
FROM (SELECT YEAR(`inserted_at`) AS `year`
    , WEEKOFYEAR(`inserted_at`) AS weekno
    , SUM(revenue) AS amount
  FROM class_customer_activity
  WHERE YEAR(`inserted_at`) = YEAR(NOW())
  GROUP BY YEAR(`inserted_at`), WEEKOFYEAR(`inserted_at`)) AS this
JOIN (SELECT YEAR(`inserted_at`) AS `year`
    , WEEKOFYEAR(`inserted_at`) AS weekno
    , SUM(revenue) AS amount
  FROM class_customer_activity
  WHERE YEAR(`inserted_at`) = YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR))
  GROUP BY YEAR(`inserted_at`), WEEKOFYEAR(`inserted_at`)) AS history
ON this.weekno = history.weekno ;

谢谢!

mysql
2个回答
1
投票

这是因为收入列不是派生表中select的一部分;它只显示为聚合sum(revenue),别名为amount

你需要把它称为this.amount(和history.amount

此外,最后一次加入应该也很可能包括year列,或者你会得到不同年份加入的weekno

我意识到上面的段落目前不是问题,因为你只选择了两年不同的年份。无论如何,为了清晰起见,将联接限定为年份可能是一个好习惯,并且为了防止将来出现问题,您可以选择在查询中包含更多年份。


0
投票

你必须在ALIASrevenue上添加amount SUB SELECT而不是FROM

SELECT 
    YEAR(`inserted_at`) AS `year`,
    WEEKOFYEAR(`inserted_at`) AS weekno,
    SUM(revenue) AS revenue

另外,你可以改为主要this.amount中的history.amountSELECT

SELECT 
    this.amount as current_amount, 
    this.weekno, 
    history.amount AS past_amount
© www.soinside.com 2019 - 2024. All rights reserved.