mysql - 从 table2 中找到列总和并用 table1 显示的最快方法
问题描述
我有两张桌子,
table1
=======================================
pid pname coldate col4
---------------------------------------
1 Tesitng Name1 2019-01-01 self
2 Tesitng Name2 2020-01-01 self
3 Tesitng Name3 2020-03-01 self2
4 Tesitng Name4 2020-04-04 self2
5 Tesitng Name5 2020-04-05 self3
在 table1 pid 中具有唯一键
table2 //which have more than 600k rows
=======================================
billid rate pid
---------------------------------------
1 30 1
2 50 1
3 40 1
4 20 2
5 60 2
6 10 3
///在table2 billid中有唯一的key
我尝试显示 table1 的所有行以及 table2 的 rate 列的总和 where table1.pid=table2.pid
结果应该是这样的
table1
=======================================================
pid pname coldate col4 total
-------------------------------------------------------
1 Tesitng Name1 2019-01-01 self 120
2 Tesitng Name2 2020-01-01 self 80
我正在使用这个查询,它对我有用,但它需要很多时间请告诉我最快的方法
SELECT t1.*,
(SELECT sum(rate) as total FROM table2 where pid=t1.pid) as total
FROM table1 t1 WHERE t1.coldate BETWEEN '2020-01-0' AND '2020-04-01'
AND t1.col4 Like 'self' ORDER BY t1.pid DESC;
我正在使用 php 和 mysql ..
解决方案
尝试这个:
SELECT
t1.*
, ttl.total
FROM table1 t1
inner join
(SELECT pid, sum(rate) as total
FROM table2
GROUP BY pid) as ttl
on ttl.pid=t1.pid
WHERE
t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
AND t1.col4 = 'self'
ORDER BY t1.pid DESC;
推荐阅读
- wpf - WPF 菜单 - 允许在禁用的菜单项中启用特定控件
- jquery - 使用 jQuery 在 cookie 中切换类和保存状态 - 如何避免闪烁和 AJAX 问题?
- angular8 - 在使用 jspdf 和 html2canvas 时,数据在分页时被切断,有时在新页面上重复
- scala - IntelliJ 无法识别 Scala 项目
- python - 从管理页面 django 打印表格
- c# - 无法将文件从本机反应发送到 .net 核心 api - 上传图片
- java - 在运行时查找 JAR 的模块依赖项
- bash - 手动作业变量设置中不接受带空格的字符串
- tensorflow - 如何检查模型是否被量化
- android - 我想以 HH: mm 格式显示 x 轴标签