Field name from ID on table 1 but name on other table

让人想犯罪 __ 提交于 2019-12-10 21:00:06

问题


This is a Firebird database.

First Table

Contacts Company_ID - job_title

Second Table

Client_id - Co_name

In contacts, I want to the job_title field to contain the co_name.

client_id and company_id are the same. Co_name correspond to company_id as well as client_id.

this:

UPDATE Contacts 
  SET Contacts.Job_title = Clients.co_name 
where company_id in (
    select client_id from clients 
    JOIN Contacts c ON Client_id=company_id where record_status='A')

gives me an error as cannot find (clients.co_name)

this other option:

UPDATE Contacts 
 JOIN Clients ON Clients.Client_id = Contacts.Client_id 
 SET Contacts.Job_title = Clients.Client_name

gives me an error on JOIN

Any other ideas please?


回答1:


UPDATE Contacts
JOIN Clients ON Clients.Client_id = Contacts.Client_id
SET Contacts.Job_title = Clients.Client_name



回答2:


To update a table from another source, you can use MERGE, which only works with Firebird 2.1 or higher:

merge into Contacts 
  using Clients
  on Contacts.Company_ID = Clients.Client_id
  when matched then update set Contacts.Job_title = Clients.co_name

Using UPDATE would be possible, but it would get ugly fast because of the lack of support for joined updates, the equivalent query would be something like the code below. I'm not sure if this will work in Firebird 1.5.

update Contacts 
  set Job_title = (select Clients.co_name from Client where Clients.Client_id = Contacts.Company_ID)
  where exists (select * from Client where Clients.Client_id = Contacts.Company_ID)

This might be a bit inefficient because of the two sub-selects that are evaluated independently.



来源:https://stackoverflow.com/questions/36473228/field-name-from-id-on-table-1-but-name-on-other-table

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