简体   繁体   中英

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

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

I have a mysql database that I want to hand off to a developer but I want to partially sanitize the data so that the two name records drop down to just initials.

I tried to modify the varchar to 1 character but mysql will not let me truncate the data, it just throws an error. I am working from a dump of the database before I hand it off. I want to obscure the names without making them all the same.

update tablename set first_name=left(first_name, 1), last_name = left(last_name, 1)

但是,正如 Gordon Linoff 提到的,如果表中有很多行,这可能会很昂贵

Updating all the rows is rather expensive because of the logging required. The most efficient way is probably to create a new 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;

Why don't you try:

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

You could use like when creating a new table so you have the same column attribute and definitions as the old table. Be sure to check the manual on the behavior of like when creating tables though, especially if you are concerned about indexing.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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