Home > Backend Development > PHP Tutorial > 请教一个mysql查询问题,送上100分

请教一个mysql查询问题,送上100分

WBOY
Release: 2016-06-23 14:39:22
Original
1350 people have browsed it

本帖最后由 SHANDIANDIAN 于 2013-12-12 12:15:27 编辑

表A                表B
uid  mid cash          uid   mid cash   number
1     1   100           1     1   101    100
2     2   105           2     1   100    100
3     3   98            3     2   105    200
4     4   55            4     2   105    300
5     5   60            5     3   60     300
6     6   70            6     3   98     300

uid 是自动增长字段  mid和cash 是关联字段

我想统计出 表B的求和数量就和下面这样,没匹配到表A就显示0,匹配通过mid和cash 两字段。请问SQL该怎么写?? 以表A为基础表
结果表
uid mid   cash  number
1    1     100  100
2    2     105  500
3    3     98   300
4    4     55    0
5    5     60    0
6    6     70    0

回复讨论(解决方案)

看这里
http://sqlfiddle.com/#!2/f5620/3

这个执行的结果还是不对啊,并没有求和

你太调皮,后来编辑过帖子了
看这个
http://sqlfiddle.com/#!2/9847b/12

create temporary table Aselect 1 as uid, 1 as mid, 100 as cashunion select 2, 2, 105union select 3, 3,  98union select 4, 4,  55union select 5, 5,  60union select 6, 6,  70;create temporary table Bselect 1 as uid, 1 as mid, 101 as cash, 100 as  numberunion select 2,     1,   100,    100union select 3,     2,   105,    200union select 4,     2,   105,    300union select 5,     3,   60,     300union select 6,     3,   98,     300;select uid,mid, cash, (select sum(number) from B where mid=A.mid and cash=A.cash) from A
Copy after login
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
Copy after login


这个返回结果是
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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template