Answer the question
In order to leave comments, you need to log in
How to populate a column with a foreign key?
Good afternoon, please tell me: there is a table with a foreign key and, accordingly, a dictionary table for it
. There is also a text field in the main table where the same is stored as in the dictionary, but with text. The task is to fill in all fields with a foreign key in accordance with this text field and dictionary
Answer the question
In order to leave comments, you need to log in
This is done by an update with subqueries.
update table tb
set tb.type_id = (select tp.id from types tp where tp.name = tb.type_name limit 1) -- выбираем подзапросом id из справочника по совпадению наименования поля в обновляемой таблице
where tb.type_id is null -- страховка, что будем обновлять не установленные значения
and exists(select 1 from types tp where tp.name = tb.type_name) -- будем ставить ключ, если есть наименование в справочнике types
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question