本文实例讲述了mysql实现多表关联统计的方法。分享给大家供大家参考,具体如下:
需求:
统计每本书打赏金额,不同时间的充值数据统计,消费统计,
设计四个表,book 书本表,orders 订单表 reward_log打赏表 consume_log 消费表 ,通过book_id与book表关联,
问题:
当关联超过两张表时导致统计时数据重复,只好用子查询查出来,子查询只能查一个字段,这里用CONCAT_WS函数将多个字段其拼接
实现:
查询代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
SELECT b.id, b.book_name, sum ( IF ( o.create_time > 0 && o.create_time < 9999999999, o.price, 0 ) ) today_pay_money, sum ( IF ( o.create_time > 0 && o.create_time < 9999999999, 1, 0 ) ) today_pay_num, sum ( IF ( o.create_time > 999 && o.create_time < 9999, o.price, 0 ) ) yesterday_pay_money, sum ( IF ( o.create_time > 999 && o.create_time < 9999, 1, 0 ) ) yesterday_pay_num, sum (o.price) total_pay_money, sum ( IF ( o.create_time > 9999 && o.create_time < 99999, 1, 0 ) ) total_pay_num, ( SELECT SUM ( total_score ) FROM book_reward_log WHERE book_id = b.id ) total_score, ( SELECT CONCAT_WS( ',' , SUM ( IF ( create_time > 0 && create_time < 998, score, 0 ) ), SUM ( IF ( create_time > 9999 && create_time < 99998, score, 0 ) ), SUM ( IF ( create_time > 99999 && create_time < 999998, score, 0 ) ) ) FROM book_consume_log WHERE book_id = b.id ) score FROM book_book b LEFT JOIN book_orders o ON b.id = o.bid GROUP BY b.id |
查询结果
score 为三个消费数,以逗号隔开
性能分析
希望本文所述对大家MySQL数据库计有所帮助。
原文链接:https://blog.csdn.net/flysnownet/article/details/90067875