带有加入的子句中的未知列

时间:2016-01-21 07:35:22

标签: mysql sql yii

我想加入3表一列总和必须与另一列进行比较

这是我的查询

SELECT 
    *, `e`.`id` AS `event_ac_id`, 
    SUM(CASE WHEN trans.gift_transaction_status = 1 
               THEN trans.event_gift_amount  
               ELSE 0 END) as amount 
FROM 
    `tbl_event_category` `cat` 
LEFT JOIN 
    `tbl_event` `e` ON e.event_category = cat.id 
LEFT JOIN 
    `tbl_organisation` `org` ON e.organisation_id = org.id 
LEFT JOIN 
    `tbl_event_gift_transaction` `trans` ON e.id = trans.event_id 
WHERE 
    cat.type ='campaign' AND is_approved=1
    AND e.funding_goal_amount <= amount 
GROUP BY 
    `event_ac_id` 
LIMIT 8
  

异常(数据库异常)&#39; yii \ db \ Exception&#39;与消息   &#39; SQLSTATE [42S22]:未找到列:1054未知列&#39;金额&#39;在   &#39; where where&#39;

3 个答案:

答案 0 :(得分:2)

您需要了解SQL是从右到左进行评估的。因此,当MYSQL解析器查找amount列时,则找不到它,从而导致错误。

manual说:

  

“可以使用AS alias_name为select_expr提供别名。别名为   用作表达式的列名,可以在GROUP BY中使用,   ORDER BY或HAVING子句。“

  

标准SQL不允许您引用WHERE中的列别名   条款。强制执行此限制是因为WHERE代码是   执行后,列值可能尚未确定。

你可以试试这个:

SELECT *, `e`.`id` AS `event_ac_id`, 
   SUM(CASE WHEN trans.gift_transaction_status = 1 THEN trans.event_gift_amount  
   ELSE 0 END) as amount 
FROM `tbl_event_category` `cat` LEFT JOIN `tbl_event` `e` 
       ON e.event_category=cat.id 
LEFT JOIN `tbl_organisation` `org` ON e.organisation_id=org.id 
LEFT JOIN `tbl_event_gift_transaction` `trans` ON e.id=trans.event_id 
 WHERE cat.type ='campaign' 
 AND is_approved=1
 HAVING  e.funding_goal_amount <= amount
 GROUP BY `event_ac_id` LIMIT 8

答案 1 :(得分:1)

聚合值的过滤器基于

可能是你需要这个

SELECT *, `e`.`id` AS `event_ac_id`, 
   SUM(CASE WHEN trans.gift_transaction_status = 1 THEN trans.event_gift_amount  
   ELSE 0 END) as amount 
FROM `tbl_event_category` `cat` LEFT JOIN `tbl_event` `e` 
       ON e.event_category=cat.id 
LEFT JOIN `tbl_organisation` `org` ON e.organisation_id=org.id 
LEFT JOIN `tbl_event_gift_transaction` `trans` ON e.id=trans.event_id 
 WHERE cat.type ='campaign' 
  AND is_approved=1
  HAVING  e.funding_goal_amount <= amount
  GROUP BY `event_ac_id` LIMIT 8

答案 2 :(得分:0)

计算值不能出现在WHERE子句中。这里只需要使用实际的列。

如果要过滤AFTERWARDS已执行WHERE子句,则可以使用HAVING语句