mysql多表查询求和

mysql多表查询求和,第1张

SELECT i.uid,sum(deposit+ddeposit+money) as allmoney FROM

另外,因为你是多个表的左联接,考虑到有NULL记录的存在,建议你用函数ifnull处理下,避免由于NULL而造成结果有误,最终改成这样:

SELECT i.uid,sum(ifnull(deposit,0)+ifnull(ddeposit,0)+ifnull(money,0)) as allmoney

FROM pw_memberinfo i LEFT JOIN pw_members m ON m.uid=i.uid LEFT JOIN pw_memberdata d ON i.uid=d.uid

where ifnull(deposit,0)+ifnull(ddeposit,0)+ifnull(money,0)>2000

我用的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

希望能对你有所帮助

有三个办法(我的连接直接写的都是id,如果不用这个连接那么就自己换掉)(1)union all(两张表直接union all),这个不会和union一样去掉重复的(万一有一个id一样,的学生,成绩也一样,那不是直接少算一科,当然如果你的id是科目id,大一大二不会重复,那就当我没说),而是直接全部排列出来,然后两张表变成一张表,直接sum就行了。你说的并集,举例就是大二有人转系,有人走,有人来,那么有人有大一成绩但是没有大二成绩,有人有大二成绩没有大一成绩,可是这两者都要显示出来,是这个意思吧。只是union all以后,外面要套一层select * from,不然如果把这个放在子查询那么就会报错,毕竟这是两张表,不是一张。(2)计算两遍一个左连接,一个右连接,得到的结果union(不是union all啊),这样去掉重复的就OK了,别忘了没有空集补0,我的isnull写的应该不规范,而且需要测试测试,毕竟也有不需要写的可能。举例,select a.id,a.student_id,a.score+isnull(b.score,0) aa from a left join b on a.id=b.idunion select b.id,b.student_id,isnull(a.score,0)+b.score aa from a right join b on a.id=b.id(3)办法差不多,不过这个是先求出只有大一成绩的,再求出只有大二成绩的,然后再求出两个成绩都有的。select a.id,a.student_id,a.score from a where a.id not in (select id from b)unionselect b.id,b.student_id,b.score from b where b.id not in (select id from a)union select a.id,a.student_id a.score+b.score score from a,b where a.id=b.id至于full join的写法,mysql我忘了有没有了,如果有更好,没有的话,那么就不那么好办了。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/7612069.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-07
下一篇 2023-04-07

发表评论

登录后才能评论

评论列表(0条)

保存