问题
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