sql - 将集合更新、插入或删除到表中

标签 sql postgresql

我在两个表 ProductTag 之间有一个 n : m 关系,称为 产品标签。它只有两列:ProductIdTagId

主键是这两列的组合。

插入这个表很简单。

但是,有了一组应该与产品相关联的新标签,我有哪些一次性更新表格的选择?

现在,在交易中,我删除了与产品关联的所有产品标签,并插入“更新的”标签。这很有效,很简单,并且不需要很长时间来编写代码。

我仍然很好奇如何更优雅地解决它,甚至可能使用 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 中的主键。

在线示例:https://rextester.com/VVL1293

关于sql - 将集合更新、插入或删除到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54215696/

相关文章:

mysql - sql 计数,其中结果大于特定数字

sql - sql中使用什么类型的百分比?

database - Django ORM 模型对象的主键中的空值

java - org.hibernate.exception.SQLGrammarException 不正确的 postgresql sql 查询

postgresql - 如何计算 PostgreSQL 中的 DATE 差异?

mysql - 用mysql提取

SQL Server - CASE FN(str) WHEN x THEN y ELSE 保留原始值而不重复函数

python - Django/python postgresql 原始 sql 问题

MySQL - 使用 WHERE 或 HAVING 子句中的结果计算每行中两列的值

postgresql - 删除所有 View PostgreSQL