我在两个表 Product
和 Tag
之间有一个 n : m 关系,称为 产品标签
。它只有两列:ProductId
和 TagId
。
主键是这两列的组合。
插入这个表很简单。
但是,有了一组应该与产品相关联的新标签,我有哪些一次性更新表格的选择?
现在,在交易中,我删除了与产品关联的所有产品标签,并插入“更新的”标签。这很有效,很简单,并且不需要很长时间来编写代码。
我仍然很好奇如何更优雅地解决它,甚至可能使用 PostgreSQL 特定功能?
示例:
假设您在此表中有 3 个条目:
product_id | tag_id
-----------+-------
1 | 2
1 | 3
1 | 6
收到更新产品标签的请求,如下所示:
product_id | tag_id
-----------+-------
1 | 3
1 | 6
1 | 7
删除了 tag_id
2 的标签,并添加了 tag_id
7 的新标签。在一条语句中实现此状态的最佳方式是什么?
最佳答案
如果我们谈论的是“通常”的标签数量——比如“数十”个标签,而不是“数千”个——那么删除/插入方法并不是一个坏主意。
然而,您可以在应用更改的单个语句中执行此操作:
with new_tags (product_id, tag_id) as (
values (1,3),(1,6),(1,9)
), remove_tags as (
delete from product_tag pt1
using new_tags nt
where pt1.product_id = nt.product_id
and pt1.tag_id <> ALL (select tag_id from new_tags)
)
insert into product_tag (product_id, tag_id)
select product_id, tag_id
from new_tags
on conflict do nothing;
上面假设 (product_id,tag_id)
被定义为 product_tag
中的主键。
关于sql - 将集合更新、插入或删除到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215696/