假设MySQL中有以下表(Table1):
FirstName Residence
Bob USA
Jane Canada
Steve China
我在MySQL中也有下表(表2):
Residence
Japan
Canada
Mexico
我想更新Table1,以便最终结果是:
FirstName Residence
Bob Japan
Jane Canada
Steve Mexico
现在,我正在考虑做以下事情:1)在两张桌子上制作一把主键2)放弃"住宿"表1中的列3)在表上进行连接。是否有更简单,更有效的方式来更新列?连接至少需要线性时间,此时应该是恒定时间操作。此外,使用多个更新查询将是乏味和缓慢的。
将一行插入MySQL数据库似乎相当快速和直接。我想知道是否有一种类似的简单方法可以将列插入MySQL数据库。
谢谢!
答案 0 :(得分:2)
有些事件可以更改表格中的行顺序,因此您确实希望有一列来区分订单。
如果出于争论的缘故,您认为可以依赖行存储的任何顺序,您可以使用以下内容:
请参阅: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
答案 1 :(得分:0)
如果我误解了,我很抱歉,但是没有一个简单的更新sqll可以修复所有这些吗?
根据OP的评论:
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
这样有帮助吗?假设你有相当数量的条目,这里有一些假代码来展示我的概念。
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