我有两张表,第一张表:表名:table1,字段(id,user_id,username,money)。第二张表:表名:table2,字段 (id,user_id,money),
现在是部门A往table1里插,部门B往table2里插,现在要做两张表的汇总:两张表money字段加起来超过10000的提取出来
select a.username,a.money as x,b.money as y from table1 as a,table2 as b where a.user_id=b.user_id group by a.user_id having x+y>=10000 order by null。
现在是这条sql:情况1,如果两张表中都有同样的user_id并且加起来超过10000,有结果。
例:table1(1,2001001,张三,5000),table2(3,2001001,张三,6000)
情况2,只有一张表中有一个user_id。无结果
例:table1(1,2001001,张三,12000),table2中没有user_id=2001001的记录。
但是情况2是满足条件的。小弟表述可能不清楚,但这个问题很棘手,各位有什么好的解决方法,请告之。谢了
现在是部门A往table1里插,部门B往table2里插,现在要做两张表的汇总:两张表money字段加起来超过10000的提取出来
select a.username,a.money as x,b.money as y from table1 as a,table2 as b where a.user_id=b.user_id group by a.user_id having x+y>=10000 order by null。
现在是这条sql:情况1,如果两张表中都有同样的user_id并且加起来超过10000,有结果。
例:table1(1,2001001,张三,5000),table2(3,2001001,张三,6000)
情况2,只有一张表中有一个user_id。无结果
例:table1(1,2001001,张三,12000),table2中没有user_id=2001001的记录。
但是情况2是满足条件的。小弟表述可能不清楚,但这个问题很棘手,各位有什么好的解决方法,请告之。谢了
如果这样就很简单,用left join
另外看你用了group by? 是否你的table2中有同一个user的很多条记录?需要总计?
那么在table1中是否也会有同一user的多条???
希望能先说明这些情况,下面这个可以先试一下,
select a.username,
a.money as x,
sum(b.money) as y
from table1 as a
left join table2 as b
on a.user_id=b.user_id
where 1
group by a.user_id
having ( x+ sum(b.money) > =10000 or x>10000 )
order by null其它情况也可以通过left join和union得出,
如果你上面的不行,我再写给你
$sql="select a.user_id,a.username,a.money as fee1,b.money as fee2 from table1 as a left join table2 as b on a.user_id=b.user_id having fee1>=10000 or fee1+fee2>=10000 union select user_id,username,money,'xxx' from table2 where money>=10000 and user_id not in (select user_id from table1)";此sql效率很低