sql 语句查出的数据为空,怎么用个if语句判断,然后作出处理。

select sum(price),userName
from food join diningcar on food.foodId=diningcar.foodId
join users on diningcar.userId=users.userId
where (comment=0 or comment=-1) and userName='zq'
group by userName
这条语句是查价格的总和,查出来的数据为空(这条语句是正确的,数据库里没有这个语句要查的相关信息)。我想做个判断。判断查出来的数据是否为空,如果为空,就给sum(price)赋值,使sum(price)=0.要保证数据库不发生改变,只是显示结果有变化。这能不能实现啊,大虾们帮帮忙

第1个回答  2011-11-10
oracle:改为
select nvl(sum(price),0),userName
from food join diningcar on food.foodId=diningcar.foodId
join users on diningcar.userId=users.userId
where (comment=0 or comment=-1) and userName='zq'
group by userName
sqlserver改为
select isnull(sum(price),0),userName
from food join diningcar on food.foodId=diningcar.foodId
join users on diningcar.userId=users.userId
where (comment=0 or comment=-1) and userName='zq'
group by userName
第2个回答  推荐于2018-06-17
可以实现,以sql server为例看:
if not exists(select userName from food join diningcar on food.foodId=diningcar.foodId join users on diningcar.userId=users.userId where (comment=0 or comment=-1) and userName='zq' group by userName)
select 0,'zq'
else
select sum(price),userName from food join diningcar on food.foodId=diningcar.foodId join users on diningcar.userId=users.userId where (comment=0 or comment=-1) and userName='zq' group by userName

方法二:
select isnull(sum(price),0),userName
from food join diningcar on food.foodId=diningcar.foodId
join users on diningcar.userId=users.userId
where (comment=0 or comment=-1) and userName='zq'
group by userName

不知道是不是你想要的结果,但是我有个疑问,你为什么不在程序里进行判断,而是要让sql语句判断呢?本回答被提问者和网友采纳
相似回答