mysql 多表运算的问题
发布网友
发布时间:2022-04-07 16:34
我来回答
共3个回答
热心网友
时间:2022-04-07 18:04
我用的MYsql 具体函数有一点点出入:而且你的表名建的太刺激了,都是in、out、return等关键字,我在表名上都添加了一个数字1,即 in1,out1,back1,return1,transfer1:
select
in1.id,
in1.amount -
if(in1.id in(select `inId` from out1), (select sum(out1.`amount`) from out1 where out1.inId=in1.id),0) +
if(in1.id in(select out1.`inId` from out1,back1 where out1.id=back1.outId), (select sum(back1.`amount`) from back1,out1 where out1.inId=in1.id and out1.id=back1.outId),0) -
if(in1.id in(select `inId` from transfer1),(select sum(transfer1.`amount`) from transfer1 where in1.id=transfer1.inId),0)-
if(in1.id in(select `inId` from return1), (select sum(return1.`amount`) from return1 where return1.inId=in1.id),0) as total
from in1
经过测试后结果为:
id, total
1. 490
2. 486
3. 489
希望能对你有所帮助
热心网友
时间:2022-04-07 19:22
相同的操作要尽量少用SQL语句,因为SQL语句不但大量占用资源.而且给数据库带来了很大的负担.
你可以在数据库里面读出来,然后在程序中用个if语句替换过来是最好的.
热心网友
时间:2022-04-07 21:13
第一次看到这种写法。。为什么不用join来写捏