SQL查询简化(EXPLAIN COST 58)

时间:2018-06-01 17:47:40

标签: mysql sql query-optimization explain

有人可以帮助简化以下查询。它的成本显示为58。

b.dueDate和b.tID是复合键。 a.tID是表1和表2之间的主键和外键。

SELECT test.tID, test.sor_acct_id, test.pmt, test.status FROM   ct.tab1 a, 
   (SELECT a.tID, a.sor_acct_id, b.dueDate, b.amt, b.status, a.pmt, 
           Row_number() OVER ( partition BY a.tID ORDER BY b.dueDate DESC) AS rn 
    FROM   ct.tab1 a 
           INNER JOIN ct.tab2 b 
                   ON a.tID = b.tID 
    WHERE  a.tID IN (SELECT a.tID 
                              FROM   ct.tab1 a 
                                     INNER JOIN 
                                     ct.tab2 b 
                                             ON a.tID = 
                                                b.tID 
                              WHERE  a.status = 'E' 
                                     AND a.pmt IS NOT NULL 
                                     AND a.pmt <> '{}' 
                                     AND b.dueDate > CURRENT_DATE - 4 
                                     AND b.dueDate < CURRENT_DATE) 
           AND b.dueDate > CURRENT_DATE - 1 
   ) test WHERE  rn = 1 
   AND test.status IN ( 'X', 'Z' ) 
   AND a.tID = test.tID

2 个答案:

答案 0 :(得分:0)

也许你会改变:

> gdb a.out
(gdb) break funnyEval
(gdb) layout split #shows assebly
(gdb) stepi #steps to the next instruction

成:

WHERE  a.tID IN (SELECT a.tID ....

答案 1 :(得分:0)

tID是tab1的主键。因此,当您说您正在查找tab1条记录时tID的记录位于一组状态为E的tab1条记录中时,您也可以简单地说:“我{&1;} m正在查找状态为E的tab1条记录。

您的查询的作用是:显示提供最终tab1状态的所有tab2条记录...

  • tab1 pmt不为空而不是&#39; {}&#39;
  • tab1状态为E
  • 最终tab2状态为X或Z
  • 最终tab2状态将于今天或将来到期
  • tab2记录的最近三天内至少有一个tab1记录到期

查询:

SELECT
  t1.tID,
  t1.sor_acct_id,
  t1.pmt,
  t2.status
FROM ct.tab1 t1
join
(
  SELECT
    tID,
    status,
    ROW_NUMBER() OVER (PARTITION BY tID ORDER BY dueDate DESC) AS rn
  FROM ct.tab2
  WHERE dueDate > CURRENT_DATE - 1
) t2 ON  t2.tID = tab1.tID AND t2.rn = 1 AND t2.status IN ('X', 'Z') 
WHERE t1.status = 'E'
  AND t1.pmt IS NOT NULL
  AND t1.pmt <> '{}'
  and t1.tID IN
  (
    SELECT tID
    FROM ct.tab2
    WHERE dueDate > CURRENT_DATE - 4
      AND dueDate < CURRENT_DATE
  );