简体   繁体   中英

How do I replace an entire column in MySQL?

Suppose I have the following table (Table1) in MySQL:

FirstName Residence
Bob       USA
Jane      Canada
Steve     China

I also have the following table (Table2) in MySQL:

Residence
Japan
Canada
Mexico

I want to update Table1 so that the final result is:

FirstName Residence
Bob       Japan
Jane      Canada
Steve     Mexico

Right now, I'm thinking of doing the following: 1) make a primary key on both tables 2) drop the "Residence" column from Table1 3) do a join on the tables. Is there an easier, more efficient way to update the column? A join would take at least linear time, when this should be a constant time operation. In addition, using multiple update queries would be tedious and slow.

Inserting a row into a MySQL database seems fairly quick and straightforward. I'm wondering if there is a similarly easy way to insert a column into a MySQL database.

Thanks!

There are events that can change the order of rows in your tables, so you really want to have a column to distinguish the order.

If for the sake of argument you thought you could rely on whatever order in which the rows happen to be stored, you could use the following:

See fiddle at: http://sqlfiddle.com/#!2/01082b/1/0

update table1 t
join ( select firstname, residence, @rw := @rw + 1 as row_number
  from table1
 cross join (SELECT @rw := 0) r ) x on t.firstname = x.firstname
join ( select residence, @rx := @rx + 1 as row_number
  from table2
 cross join (SELECT @rx := 0) r ) y on y.row_number = x.row_number
set t.residence = y.residence

I am sorry if I misunderstood, but doesn't a simple update sqll could fix all these??

According to OP's comment:

suppose I want to go to the Residence column, load it into Java, do some processing on it (e.g. strip whitespace, add capital city, capitalize all letters, etc), and then load it back into MySQL. I would rather not do the processing in SQL since I have to make extensive changes

so would this help? Assuming you'll have a considerable amount of entries, here are some fake code to show my concept.

resultset = db.query("select FirstName, Residence from table");
hashmap = process(resultset);
String createSql = "create table temp (firstname, residence)";
db.execute(createSql);    
StringBuffer sb = "insert into temp values ";
for (int i=0; i<hashmap.size;i++){
    //hashmap needs to be loop with iterator, this is just me being lazy
    sb.append("("+hashmap(firstname)+", "+hashmap(residence)+")");
}
db.execute(sb.toString());
db.execute("update table inner join temp on table.firstname=temp.firstname set table.residence = temp.residence")
//remove temp after this maybe

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