【问题标题】:Unknown Column In Where Clause With Join带有连接的 Where 子句中的未知列
【发布时间】:2016-01-21 07:35:22
【问题描述】:

我想加入 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

异常(数据库异常)'yii\db\Exception' 带有消息 'SQLSTATE [42S22]:未找到列:1054 中的未知列 'amount' 'where子句'

【问题讨论】:

    标签: mysql sql yii


    【解决方案1】:

    计算值不能在WHERE 子句上。那里只需要使用实际的列。

    如果要在WHERE 子句执行后过滤,可以使用HAVING 语句

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 我已经尝试过SUM(CASE WHEN trans.gift_transaction_status = 1 THEN trans.event_gift_amount ELSE 0 END)&gt;e.funding_goal_amount 还有什么解决方案
      • @KakulSarma:- 尝试使用 HAVING 子句而不是 WHERE 子句来使用您的条件。
      【解决方案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
        HAVING  e.funding_goal_amount <= amount
        GROUP BY `event_ac_id` LIMIT 8
      

      【讨论】:

        猜你喜欢
        • 2014-09-20
        • 2011-06-03
        • 1970-01-01
        • 1970-01-01
        • 2021-09-19
        • 2020-06-28
        • 2021-07-02
        • 2019-08-14
        相关资源
        最近更新 更多