MySQL联结查询和子查询

2018-2-24 16:18:12 星期六

今天需要统计一个运营活动的数据, 涉及三个表, 分组比较多

活动描述:

每个人可以领取多张卡片,  好友也可以赠送其卡片, 20或40张卡片可以兑换一个奖品

要求统计出:

1. 每个用户的个人信息, 2. 领取的卡总数, 3. 自己领的卡的数目, 4. 好友送的卡的数目, 5. 兑换奖品的数目

遇到的问题有:

1. 要先用group by 得到每个用户总共的卡数量,  再用group by 得到每个用户被赠送的卡数量, 然后对两者做减法得到自己领取卡的数量 // 减法, 第1行

2. 每个用户可以兑换多个奖品, 因此要把uid相同的多行奖品记录连接成一行, 这个用到了 group by + group_concat()  //第4行

SQL:

下边的SQL整体来看是几个left join ,  而join的表不是表名, 是一个子查询

1 select a.uid, c.nickname, c.mobile, a.uid_cards, (a.uid_cards - b.send_uids) as self_cards, b.send_uids, c.regdate, FROM_UNIXTIME(c.regdate, '%Y-%m-%d'), d.award_ids 
2 from (select uid, count(*) as uid_cards from tabale1 group by uid) as a
3 left join (select uid, count(*) as send_uids from tabale1 where send_uid > 0 group by uid) as b on a.uid = b.uid
4 left join (select uid, group_concat(award_id) as award_ids  from table2 group by uid) as d on a.uid = d.uid
5 left join table3 as c on a.uid = c.uid;

table1:  每个人的领取卡片记录表

table2: 每个人的兑换奖品记录列表

table3: 用户信息表

 

posted @ 2018-02-24 16:39  myD  阅读(537)  评论(0编辑  收藏  举报