关于一条SQL语句的优化

nightgoblin nightgoblin 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
目前有这样一张表,查询要求:查询出当每个用户交易金额累计达到70时的交易时间。
源码:

DROP TABLE IF EXISTS t_g;
CREATE TABLE t_g
(t_id BIGINT AUTO_INCREMENT,
t_userid VARCHAR(20) DEFAULT '' COMMENT '用户id',
t_je VARCHAR(20) DEFAULT '' COMMENT '交易金额',
t_date VARCHAR(20) DEFAULT '' COMMENT '交易时间',
PRIMARY KEY(t_id)
);
-- 创建索引
CREATE INDEX i_a ON t_g (t_userid,t_date);

INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','20','20160701');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','10','20160702');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','15','20160703');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','15','20160704');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','20','20160705');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','50','20160706');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','20','20160707');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('A','20','20160708');

INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('B','40','20160701');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('B','20','20160702');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('B','15','20160703');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('B','15','20160704');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('C','20','20160701');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('C','50','20160702');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('C','20','20160703');
INSERT INTO t_g (t_userid,t_je,t_date) VALUES ('C','20','20160704');


我的查询语句是这样的写的:

select x.t_userid,MIN(x.t_date) from
(select a.t_userid,a.t_date,(select sum(t_je) from t_g where t_userid = a.t_userid and t_date <= a.t_date
)total from t_g a)x
where x.total/100 > 70 GROUP BY x.t_userid;

这样写可以是实现查询的功能,但是这张表有30万数据的时候,运行速度超级慢,大概需要2分钟。请问高手们,这句该怎么样优化,或者有其他更好的办法实现没,用存储过程也可以,只要能提升性能。
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
nightgoblin
MySQL 57,062 成员 56,759 内容