在MySQL中我们如何在查询中使用已定义的变量

时间:2013-04-03 04:17:37

标签: mysql

set @total_balance=0;
select total_balance=if(a.transaction_type='+c') then total_balance=total_balance+a.tran_amount
else if(a.transaction_type='-p'or '-r') then total_balance=total_balance-a.tran_amount
END
from lib_user_account a
where employee_Id='1004';

2 个答案:

答案 0 :(得分:2)

SUM(IF(a.transaction_type='+c', a.tran_amount, -a.tran_amount))

答案 1 :(得分:1)

最好在查询中使用sum函数,因为zerkms已经提到但是要回答关于如何在MYSQL中使用用户定义变量的问题,您可以在查询中以下列方式使用它

select 
  @total_balance:=if(a.transaction_type='+c', @total_balance+a.tran_amount, if(a.transaction_type='-p' or a.transaction_type='-r', @total_balance-a.tran_amount, a.tran_amount))
from 
  lib_user_account a
join 
  (select @total_balance:=0) userVar
where 
  employee_Id='1004';

REFER FOR MORE INFO ABOUT USER DEFIND VARIABLE