mysql多表关联统计

mysql多表关联统计子查询统计

需求:

统计每本书打赏金额,不同时间的充值数据统计,消费统计,

设计四个表,book 书本表,orders 订单表  reward_log打赏表   consume_log 消费表 ,通过book_id与book表关联,

mysql多表关联统计_第1张图片

问题:

当关联超过两张表时导致统计时数据重复,只好用子查询查出来,子查询只能查一个字段,这里用CONCAT_WS函数将多个字段其拼接

实现:

查询代码如下

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

查询结果

 

mysql多表关联统计_第2张图片

score 为三个消费数,以逗号隔开

性能分析

你可能感兴趣的:(mysql,mysql联合统计)