【问题标题】:Speed up UPDATE from another table从另一个表加速 UPDATE
【发布时间】:2018-10-29 14:57:03
【问题描述】:

我有以下代码:

UPDATE tableOne
SET columnOne = CASE
                 WHEN tableOne.columnTwo LIKE '%-02-%' OR tableOne.columnTwo LIKE '%-03-%' OR
                      tableOne.columnTwo LIKE '%-04-%' OR
                      tableOne.columnTwo LIKE '%-05-%' OR
                      tableOne.columnTwo LIKE '%-06-%' OR
                      tableOne.columnTwo LIKE '%-07-%' OR tableOne.columnTwo LIKE '%-08-%' OR
                      tableOne.columnTwo LIKE '%-09-%'
                         THEN tableTwo.columnOne :: text
                 ELSE tableOne.columnOne
    END

FROM tableTwo
WHERE tableTwo.tableId = tableOne.tableId

我有两张桌子。 tableOne 由 1 亿行(和 40 列)组成,tableTwo 由 9000 万行组成。上述查询已经进行了超过 2 天。我不确定它是否会完成。有没有办法优化查询?

如果有帮助,LIKE 会执行以下操作: 检查字符串(例如2018-06-30 08:20:17)是否列出了月份。如果是,则从tableTwo 中选择值(并将其转换为输入text),否则保留自身值(已输入text)。

【问题讨论】:

  • 为什么不将日期/时间存储为日期/时间(数字)字段?这是您可以做出的主要改进。
  • 试试:SUBSTRING(tableOne.columnTwo FROM 6 FOR 2) BETWEEN '02' AND '09'...
  • @AndyG 如果一开始是date 类型,性能会显着提高吗?
  • 我本来是这么想的,应该尽量避免搜索Like '%anything%,尤其是8次以上。也可以尝试使用连接,而不是 WHERE 子句,尽管数据库可能会优化差异。
  • 100M 行在文本字段中带有时间戳“......因为我们无法在一开始就导入数据......” 叹息

标签: sql postgresql performance


【解决方案1】:

case 条件移至where 子句:

UPDATE tableOne
    SET columnOne = tableTwo.columnOne::text
FROM tableTwo
WHERE tableTwo.tableId = tableOne.tableId AND
      tableOne.columnTwo ~ '-0[2-9]-' and
      tableOne.columnOne is distinct from tableTwo.columnOne::text;

正则表达式并不比一堆喜欢快多少。这里的胜利在于不更新不需要更新的行。如果tableOne.columnTwo的格式是已知格式,则可以使用子串操作。

【讨论】:

  • '-0[2-9]-' 用于正则表达式,可能会快一点。
  • 并在 WHERE 子句中添加AND columnOne <> tableTwo.columnOne::text 以抑制幂等更新。
【解决方案2】:

如果月份在 02 到 09 之间才更新呢

UPDATE tableOne
SET columnOne = tableTwo.columnOne :: text
FROM tableTwo
WHERE tableTwo.tableId = tableOne.tableId 
  AND SUBSTRING(tableOne.columnTwo FROM 6 FOR 2) BETWEEN '02' AND '09'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    相关资源
    最近更新 更多