【问题标题】:SQL how to force column to be unique if that row's foreign ID is the same?如果该行的外部 ID 相同,SQL 如何强制列唯一?
【发布时间】:2015-09-28 01:57:05
【问题描述】:

在我的架构中,我有一个表

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

我基本上想做的是,当我在这个表中插入行时:

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

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

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

我怎样才能做到这一点?

另外,现在我断言列词必须是唯一的,但我只希望它每个 remote_id 都是唯一的。

【问题讨论】:

    标签: mysql sql database sql-update


    【解决方案1】:

    您需要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 对上有一个唯一索引,这就是您想要强制执行该条件的内容。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 谢谢,但现在我如何更新我的插入语句,以便它更新计数值,如果它已经存在于 remote_id?
      • 问题被标记为 mysql,所以不确定你是否可以在 plsql 中写任何东西 - 那不只是 Oracle 吗?
      • 是的,请不要使用 PL-SQL。值得庆幸的是,该语言仅包含在 Oracle 中。
      猜你喜欢
      • 2023-03-09
      • 2016-08-03
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多