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
答案 0 :(得分:2)
使用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
答案 1 :(得分:2)
您应使用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
答案 2 :(得分:1)
我认为它会起作用,
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 sum(credit) > 0
group by user_id
或者您也可以使用Haven子句获得相同的结果。
喜欢
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 sum(credit) > 0
答案 3 :(得分:0)
使用having
和acc.user_id,member.nickname
,group.balance中的member.balance
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 acc.user_id, member.nickname,member.balance
HAVING ttl > 0
答案 4 :(得分:0)
您需要使用子查询来获取ttl列,因为它是派生列
select * from
(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
)bal
Where ttl>0
答案 5 :(得分:0)
在where
子句中使用列别名不能像提到的here那样工作。
- 首先形成 from 子句中所有表的乘积。
然后评估- where 子句以消除不满足条件的行 搜索条件。
- 接下来,使用 group by 子句中的列对行进行分组。
- 然后,具有不满足search_condition的组 。
- 接下来, select 子句目标列表中的表达式为 已评估。
- 如果select子句中存在 distinct 关键字,请复制行 现在被淘汰了。
- 对每个子选择进行评估后,将获取联合。
- 最后,结果行将根据列进行排序 在 order by 子句中指定。
where
子句在select
之前进行求值,因此尚不知道ttl
是什么。