MySQL 非唯一字段上的重复键
我有一个包含各种参数的表。 表的结构为: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ON DUPLICATE KEY 子句不仅有效在主键上:
因此除非我遗漏了一些明显的东西,否则您只需要在要使其唯一的列组合上创建唯一索引:
The ON DUPLICATE KEY clause does not only work on the primary key:
So unless I'm missing something obvious you simply need to create a unique index on the column combination you want to make unique: