create temporary table A select 1 as uid, 1 as mid, 100 as cash union select 2, 2, 105 union select 3, 3, 98 union select 4, 4, 55 union select 5, 5, 60 union select 6, 6, 70;create temporary table B select 1 as uid, 1 as mid, 101 as cash, 100 as number union select 2, 1, 100, 100 union select 3, 2, 105, 200 union select 4, 2, 105, 300 union select 5, 3, 60, 300 union select 6, 3, 98, 300;select uid,mid, cash, (select sum(number) from B where mid=A.mid and cash=A.cash) from A 1 1 100 100 2 2 105 500 3 3 98 300 4 4 55 5 5 60 6 6 70 写测试数据花的时间比写查询指令的时间多十倍都不止
这个就是我想要的 select a.*,if(t.number is null,0,t.number) as number from a left join (select b.mid,b.cash,sum(b.number) as number from b group by mid,cash) as t on t.mid=a.mid and t.cash=a.cash
select a.uid, a.mid, a.cash, sum(b.number) from testa as a left join testb as b on a.mid=b.mid and a.cash = b.cash group by a.mid, a.cash这个返回结果是 uid mid cash sum(b.number) 1 1 100 100 2 2 105 500 3 3 98 300 4 4 55 5 5 60 6 6 70
http://sqlfiddle.com/#!2/f5620/3
看这个
http://sqlfiddle.com/#!2/9847b/12
select 1 as uid, 1 as mid, 100 as cash
union select 2, 2, 105
union select 3, 3, 98
union select 4, 4, 55
union select 5, 5, 60
union select 6, 6, 70;create temporary table B
select 1 as uid, 1 as mid, 101 as cash, 100 as number
union select 2, 1, 100, 100
union select 3, 2, 105, 200
union select 4, 2, 105, 300
union select 5, 3, 60, 300
union select 6, 3, 98, 300;select uid,mid, cash, (select sum(number) from B where mid=A.mid and cash=A.cash) from A
1 1 100 100
2 2 105 500
3 3 98 300
4 4 55
5 5 60
6 6 70 写测试数据花的时间比写查询指令的时间多十倍都不止
select a.*,if(t.number is null,0,t.number) as number from a left join
(select b.mid,b.cash,sum(b.number) as number from b group by mid,cash) as t
on t.mid=a.mid and t.cash=a.cash
select a.uid, a.mid, a.cash, sum(b.number) from testa as a left join testb as b on a.mid=b.mid and a.cash = b.cash group by a.mid, a.cash这个返回结果是
uid mid cash sum(b.number)
1 1 100 100
2 2 105 500
3 3 98 300
4 4 55
5 5 60
6 6 70