我想加入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;
答案 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
语句