MySQL 非唯一字段上的重复键

发布于 2024-11-04 07:13:24 字数 605 浏览 3 评论 0原文

我有一个包含各种参数的表。 表的结构为:id、object_id、param_name、param_value

以下代码可以工作,但它会附加结果而不是更新结果。 事实是我不能使用 ON DUPLICATE KEY< /a> 因为我的字段不是唯一的(当然 id 除外)

INSERT INTO `params_table` (`object_id`, `param_name`, `param_value`)
SELECT
A.id AS my_object_id,
'XYZ' AS my_param_name,
IF(TMP.abc IS NULL,0,1) AS my_param_value
FROM
ref_table AS A
LEFT JOIN tmp_table AS TMP ON TMP.abc = A.abc
ON DUPLICATE KEY
UPDATE `param_value` = IF(TMP.abc IS NULL,0,1);

I have a table containing all sort of parameters.
The structure of the table is : id, object_id, param_name, param_value

The following code works, but it appends results instead of updating them.
The fact is that I can't use ON DUPLICATE KEY because my fields are non-uniques (except for id of course)

INSERT INTO `params_table` (`object_id`, `param_name`, `param_value`)
SELECT
A.id AS my_object_id,
'XYZ' AS my_param_name,
IF(TMP.abc IS NULL,0,1) AS my_param_value
FROM
ref_table AS A
LEFT JOIN tmp_table AS TMP ON TMP.abc = A.abc
ON DUPLICATE KEY
UPDATE `param_value` = IF(TMP.abc IS NULL,0,1);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我家小可爱 2024-11-11 07:13:24

ON DUPLICATE KEY 子句不仅有效在主键上:

如果您指定ON DUPLICATE KEY
UPDATE,并插入一行
会导致重复值
UNIQUE 索引或 PRIMARY KEY、UPDATE
执行旧行的操作

因此除非我遗漏了一些明显的东西,否则您只需要在要使其唯一的列组合上创建唯一索引:

ALTER TABLE params_table
ADD UNIQUE unique_object_param(object_id,param_name);

The ON DUPLICATE KEY clause does not only work on the primary key:

If you specify ON DUPLICATE KEY
UPDATE, and a row is inserted that
would cause a duplicate value in a
UNIQUE index or PRIMARY KEY, an UPDATE
of the old row is performed

So unless I'm missing something obvious you simply need to create a unique index on the column combination you want to make unique:

ALTER TABLE params_table
ADD UNIQUE unique_object_param(object_id,param_name);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文