简体   繁体   English

SQL 修剪非常慢

[英]SQL TRIM VERY SLOW

We have millions of records in table.我们在表中有数百万条记录。 We have a column that has white-spaces after the text.我们有一列在文本后面有空格。 We have tried the following:我们尝试了以下方法:

update schema.table_name 
set column_name = trim(column_name);

It is very slow 20+ hours. 20多个小时非常慢。 We have tried to use the WHERE clause and the RTRIM too however it made no difference.我们也尝试使用 WHERE 子句和 RTRIM,但没有任何区别。 What can be done to speed up this trim?可以做些什么来加速这种修剪?

What is making the query slow is probably not the trim() but rather having to update every row.使查询变慢的原因可能不是trim()而是必须更新每一行。 The trim() would be slow if the column is particularly large.如果列特别大, trim()很慢。

Assuming that only a few rows need to be updated, then you can filter with a where :假设只需要更新几行,那么您可以使用where进行过滤:

update schema.table_name
    set column_name = trim(column_name)
    where column_name like ' %' or column_name like '% ';

If most rows need to be updated, then reconstructing the table is often the fastest solution:如果大多数行需要更新,那么重建表通常是最快的解决方案:

create table temp_table_name
    select . . ., -- all the other columns
           trim(column_name) as column_name
    from t;

truncate table table_name;  -- BACKUP THE TABLE FIRST!

insert into table_name
    select *
    from temp_table_name;

The exact syntax might vary by database.确切的语法可能因数据库而异。 Also, this is tricky if you have auto-incrementing columns.此外,如果您有自动递增的列,这很棘手。 But the idea is the same.但想法是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM