2015-10-26 15 views

回答

1
update users 
inner join users_temp using (id) 
set users.name = users_temp.name, 
users.department_id = users_temp.department_id 

delete from users 
where not exists (select * from users_temp where users_temp.id = users.id) 
+0

爲什麼,如果你用'左JOIN'只是要過濾掉'WHERE'子句中的不匹配行?使用「INNER JOIN」,以便它們不在第一位。 – Barmar

+0

Barmar:你說得對。 – pigmej

+0

謝謝,它工作。如果查詢不存在於用戶中,請添加一個查詢,以將users_temp中的一行復制到用戶中? – Dean

2

您可以通過在更新中添加聯接來完成此操作。

UPDATE users u 
INNER JOIN users_temp ut on u.id = ut.id //or whatever the matching fields are 
SET u.name = ut.name, u.department_id = ut.department_id; 

我敢肯定有人會在第二個查詢更高效的例子,但這會做的伎倆:

Delete all rows which has no id existing in another table