SQL 如果该行的外部 ID 相同,如何强制列唯一?

SQL how to force column to be unique if that row's foreign ID is the same?

在我的架构中,我有一个 table 和

id | word | count | remote_id
-----------------------------

我基本上想这样做的是,当我向 table 中插入行时,例如:

insert into table (word, count, remote_id) VALUES ('cat', 10, 2);

首先,如果 'cat' 已经存在且 remote_id=2,我希望 'cat' 的计数最终值为 10 + 它的现有值。

如果不存在,将照常插入。

我怎样才能做到这一点?

此外,现在我断言列词必须是唯一的,但我只希望它根据 remote_id.

是唯一的

在模式中向两列添加唯一约束

Alter table table_name add unique 'uni_undex'  (word, remote_id)

编辑: 计数 您可以在 pl sql 中插入事件后编写触发器 或 select +(更新或插入)

您需要 id 列吗?如果您可以将 word, remote_id 对作为主键,那么您可以使用 on duplicate key syntax

insert into table (word, count, remote_id) VALUES ('cat', 10, 2)
on duplicate key update count = count +values(count);

编辑:我的观点是正确的。您可以使用此语法,即使它不是主键,只要您在 word, remote_id 对上有一个唯一索引,这就是您想要强制执行该条件的唯一索引。