Oracle Update query with join

雨燕双飞 提交于 2020-01-06 14:38:09

问题


There are tow tables. first one is expenses and second one is expenses_items.

There are 2 columns in expenses table as expns_id and expns_job_type.

There are 2 columns in expenses_items table as expns_id (foreign key from expenses table) and group.

I need to update group in expenses_items table and set it's value as development where value of expns_job_type in expenses table like new building.

I have tried below query. but not worked.

update expenses_items
set expenses_items."group" = 'development'
 join expenses ON 
 expenses_items.expns_id = expenses.expns_id 
where expenses.expns_job_type like 'new building'

How could i do this ?


回答1:


You can use subquery in where clause to limit your update request:

UPDATE expenses_items ei SET
  group = 'dvelopment'
WHERE EXISTS(
  SELECT expns_id FROM expenses e
  WHERE e.expns_id = ei.expns.id
    AND expns_job_type LIKE 'new building'
)

Also its may be typo, however you using LIKE clause without using wildcards. If you need exact match - use = instead of LIKE




回答2:


Oracle uses UPDATE syntax what is differ from that SQL Server support. Please see Oracle documentation for UPDATE and MERGE statements:

http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_10007.htm

http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9016.htm#i2081218

In your case this should be something like

update expenses_items
set expenses_items."group" = 'development'
where exists (select * from expenses
where expenses_items.expns_id = expenses.expns_id 
and expenses.expns_job_type like 'new building'
)

or

merge into expenses_items using 
(
 select expenses.expns_id
 from expenses 
 where expenses.expns_job_type like 'new building'
) src on (expenses_items.expns_id = src.expns_id)
when matched then 
  update set expenses_items."group" = 'development'



回答3:


Oracle doesn't support "update with join" syntax. You can do the following instead :

update expenses_items e
set group = 'development'
where exists 
(
 select 1 
 from expenses 
 where expns_id = e.expns_id and expns_job_type like '%new building%'
)


来源:https://stackoverflow.com/questions/22740758/oracle-update-query-with-join

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