有什么方法可以优化这个查询,因为我只更新表而不是插入新行?

时间:2017-01-04 23:09:46

标签: mysql

new_table的结构是它永远不会插入新行,但只会更新现有行。

目前我正在使用以下查询。有没有办法优化这个(在性能方面)以实现更快的行更新?

INSERT INTO new_table (hash, pages, visits, last_visit)
   SELECT A.hash, COUNT(B.id), A.visits, MAX(B.timestamp)
      FROM audience A
JOIN behaviour B ON B.hash = A.hash
GROUP BY A.hash
   ON DUPLICATE KEY UPDATE
      new_table.pages=VALUES(pages), 
      new_table.visits=VALUES(visits), 
      new_table.last_visit=VALUES(last_visit)

1 个答案:

答案 0 :(得分:1)

使用UPDATE而不是INSERT

UPDATE new_table n
JOIN audience AS a on a.hash = n.hash
JOIN (
    SELECT hash, COUNT(*) AS pages, MAX(timestamp) AS last_visit
    FROM behaviour
    GROUP BY hash) AS b ON b.hash = n.hash
SET n.pages = b.pages, n.visits = a.visits, n.last_visit = b.last_visits