从 table2 中查找列总和并用 table1 显示的最快方法

Fastest way to find sum of column from table2 and show it with table1

我有两个table,

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有唯一键

我尝试显示 table1 的所有行以及 table2 的比率列的总和,其中 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..

您使用相关子查询的方法非常好,而且可能是最快的方法。

为了性能,您需要 table2(pid, rate) 上的索引。

您还可以考虑 table1(col4, coldate, pid) 上的索引,并重写 col4 上的条件以使用显式相等而不是不带通配符的模式匹配(尽管可能数据库确实优化了它已经):

SELECT 
    t1.*,
    (SELECT sum(rate) as total FROM table2 where pid=t1.pid) as total
FROM table1 t1 
WHERE 
    t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
    AND t1.col4 = 'self' 
ORDER BY t1.pid DESC;

不得已,你也可以在SELECT子句中枚举出table1的所有列,并加入到索引中,希望能覆盖 - table1(col4, coldate, pid, name):

SELECT 
    t1.pid,
    t1.name,
    t1.coldate,
    t1.col4,
    (SELECT sum(rate) as total FROM table2 where pid=t1.pid) as total
FROM table1 t1 
WHERE 
    t1.coldate BETWEEN '2020-01-01' AND '2020-04-01'
    AND t1.col4 = 'self' 
ORDER BY t1.pid DESC;

试试这个:

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;