首页 > 解决方案 > 从 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 ..

标签: mysqlsqlgroup-bymysql-workbenchquery-optimization

解决方案


尝试这个:

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;

推荐阅读