工作中有一需求,要根据多个表的数据统计情况来更新另外一个表中的某个字段,折腾了会才写出如下sql:
--最终版更新语句 update moka_user_usage t set portfolionumber = (select ta.pnum from (select sum(pnum) pnum, pomuid from ((select count(om.userid) pnum, om.userid pomuid from MOKA_PORTFOLIO p, MOKA_PORTFOLIO_CATEGORY c, om_user om where p.type_id = c.type_id and p.verify_flag = '1' and p.open_flag = '0' and om.userid = p.user_id -- and t.userid = om_user.userid group by om.userid) union all select * from (select count(mom.username) mctnum, mom.userid mctuid from mct_works_type_mapping mtp, mct_works mct, om_user mom where mtp.works_id = mct.works_id and mct.cp_id = mom.username and mct.state = '1' group by mom.userid)) group by pomuid ) ta where ta.pomuid = t.userid)
当然这个和业务相关,我贴出来只想记录下。
在写这个sql时,遇到个小问题,不知该如何解决,问题意思大概如下:
有两个表ta(num1,id1) tb(num2,id2)
ta表数据如下:
NUM1 ID1
1 100
2 101
5 107
4 108
9 210
tb的数据如下:
NUM2 ID2
3 100
8 104
5 301
10 101
20 710
45 107
要将ta和tb中的数据合并,如果ta和tb中id相同的话,则把num1和num2相加,开始没想要分组,
其实很简单,sql如下:
select sum(num1), id1 from (select * from TESTA a Union All select * from TESTB b) group by id1
顺便温故了下sql,union all 为合并两个结果集,不会合并重复的行,而union 则会合并重复的行。