Updating a column in one table through a column in another table

痞子三分冷 提交于 2019-12-12 11:50:19

问题


I have 2 tables 'A' and 'B'. Both have a common column 'name' and linked with each other by a column 'id'. The column 'name' in the table A is empty whereas it has data in table B. My task is to fill all the data in that column from table B to table A with corresponding ids.

I'm using the following query:

UPDATE A
SET A.name = (SELECT B.name from B WHERE A.id = B.id)
WHERE EXISTS
(SELECT B.name from B)

As soon as I run the query in SQL developer, it just freezes and i have to force close it. Can anyone tell me what's wrong with the query?


回答1:


Try this one instead:

UPDATE A
SET A.name = (SELECT B.name FROM B WHERE B.id = A.id AND B.name IS NOT NULL)
WHERE a.name IS NULL;

Since you're using Oracle, here's the reference for IS NOT NULL.

Here's the SQL Fiddle so that you can play with it: http://sqlfiddle.com/#!4/a5ad0/3




回答2:


I'm not sure from the above conversation whether you made any changes beyond indexing your data, but you should include a WHERE EXISTS clause as mentioned. The complete query should look like this:

UPDATE A
   SET A.name = ( SELECT B.name FROM B WHERE B.id = A.id )
 WHERE EXISTS ( SELECT 1 FROM B WHERE B.id = A.id )

The WHERE EXISTS clause in your original query won't do much of anything except check to see if there is at least one non-NULL value of name in B.



来源:https://stackoverflow.com/questions/12267329/updating-a-column-in-one-table-through-a-column-in-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!