您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

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

2024/3/29 20:20:06发布5次查看
请教一个mysql查询问题,送上100分
本帖最后由 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/9847b/12
------解决方案--------------------
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.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
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录