mysql - sql 在查询子句中使用求和结果

标签 mysql sql

select acc.user_id
     , member.nickname
     , sum(credit) as ttl 
     , member.balance
  from account_history as acc
  left 
  join member
    ON acc.user_id = member.user_id
 where balance > 0 
   and balance <50
 group 
    by user_id 

我想显示 ttl ( sum(credit) ) > 0 ,

所以我改成

select acc.user_id,member.nickname, sum(credit) as ttl ,member.balance
from account_history as acc left join member 
ON acc.user_id=member.user_id 
where balance > 0 and balance <50 and ttl > 0
group by user_id 

但它变成了错误。未找到列 ttl

最佳答案

使用 having 子句中的值应该有效:

select acc.user_id,member.nickname, sum(credit) as ttl ,member.balance
from account_history as acc 
    left join member ON acc.user_id=member.user_id 
where balance > 0 and balance <50 
group by user_id 
having  ttl > 0

where 子句中你不能使用别名

另见 https://dev.mysql.com/doc/refman/8.0/en/problems-with-alias.html

关于mysql - sql 在查询子句中使用求和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55351823/

相关文章:

sql - sp_OAGetProperty 返回 NULL,且 OUT 变量声明为 MAX

sql - 使用 Rails 和 Postgresql 迁移时不填充默认值

mysql - MariaDB 默认 float 不能包含小数位

MySQL错误: The used SELECT statements have a different number of columns

mysql - 尝试移动 `/var/lib/mysql`后访问Mysql失败

mysql - 数据库关系、外键和图表 - MySQL workbench

PHP 对存储为字符串的数字进行自然排序不起作用

PHP - mysqli - 检查表是否已插入值

php - 从sql中区分foreach循环中的重复项

sql - mysql基于日期的最后结果