PostgreSQL 如果外键存在则插入 [英] PostgreSQL insert if foreign key exists
本文介绍了PostgreSQL 如果外键存在则插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅当外键(在本例中为模型)存在时,如何才能在带有外键引用的表中插入新行?
How can I insert a new row in a table with a foreign key reference only if the foreign key (in this case model) exists?
目前我有以下声明:
INSERT INTO furniture (model, type) VALUES (modelA, chair)
推荐答案
如果 FK 不存在,请使用不返回任何内容的 SELECT.
Use a SELECT that returns nothing if the FK does not exist.
INSERT INTO furniture (model, type)
select 'modelA', 'chair'
where exists (select *
from model
where model.model = 'modelA');
你没有告诉我们引用的表叫什么.我假设它是 model
- 您需要将其调整为真实姓名.
You did not tell us what the referenced table is called. I assumed it's model
- you need to adjust that to the real names.
这篇关于PostgreSQL 如果外键存在则插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文