将 first_name 和 last_name 列中的名称截断为 1 个字符的最有效方法是什么?

What's the most efficient way of truncating the names in a first_name and last_name column to 1 character?

将 first_name 和 last_name 列中的姓名截断为 1 个字符的最有效方法是什么?

我有一个 mysql 数据库,我想将其交给开发人员,但我想对数据进行部分清理,以便两个姓名记录下降到只有首字母。

我试图将 varchar 修改为 1 个字符,但 mysql 不允许我截断数据,它只是抛出一个错误。在我移交之前,我正在处理数据库的转储。我想隐藏名字而不让它们都一样。

由于需要日志记录,更新所有行的成本相当高。最有效的方法可能是创建一个新的 table:

create table for_developer as
    select left(first_name, 1) as first_name, left(last_name, 1) as last_name,
           . . . -- rest of columns
    from t;
update tablename set first_name=left(first_name, 1), last_name = left(last_name, 1)

但是,正如 Gordon Linoff 提到的,如果 table

中有很多行,这可能会很昂贵

你为什么不试试:

Update "you_table"
SET first_name = LEFT(first_name,1), 
last_name = LEFT(last_name,1);

您可以在创建新 table 时使用 like,这样您就拥有与旧 table 相同的列属性和定义。但是,在创建 table 时,请务必检查 manual 关于 like 的行为,尤其是当您担心索引时。

create table new_table like old_table;

insert into new_table

select left(first_name, 1) as first_name, left(last_name, 1) as last_name, ..-- rest of columns
from old_table;