当重复项是不同的唯一列时,如何防止 MySQL 在使用 ON DUPLICATE KEY UPDATE 时自动递增主键?
考虑下表:
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| vendor_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| vendor_name | varchar(100) | NO | UNI | NULL | |
| count | int(10) unsigned | NO | | 1 | |
+-------------+------------------+------+-----+---------+----------------+
我有以下 MySQL 查询:
INSERT INTO `table`
(`vendor_name`)
VALUES
('foobar') ON DUPLICATE KEY UPDATE `count` = `count` + 1
此查询的目的是将新的供应商名称插入表中,如果供应商名称已存在,则列计数应增加 1。当前列的 key 也会自动递增。在这些情况下如何防止MySQL自动递增主键?有没有一种方法可以通过一个查询来完成此操作?
谢谢。
Consider the following table:
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| vendor_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| vendor_name | varchar(100) | NO | UNI | NULL | |
| count | int(10) unsigned | NO | | 1 | |
+-------------+------------------+------+-----+---------+----------------+
I have the following MySQL query:
INSERT INTO `table`
(`vendor_name`)
VALUES
('foobar') ON DUPLICATE KEY UPDATE `count` = `count` + 1
The intent of this query is to insert a new vendor name to the table and in case the vendor name already exists, the column count should be incremented by 1. This works however the primary key of the current column will also be auto-incremented. How can I prevent MySQL from auto-incrementing the primary key in these cases? Is there a way to do this with one query?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过在值已经存在时使用 UPDATE 语句:
我尝试了 ON DUPLICATE KEY UPDATE, REPLACE INTO 的替代方法:
它更新了计数和vendor_id,所以情况更糟
......数据不关心数字是否不连续,只关心值是唯一的。如果您可以忍受这一点,我会使用 ON DUPLICATE UPDATE 语法,尽管我承认这种行为很奇怪(考虑使用 INSERT 语句是可以理解的)。
By using an UPDATE statement when the value already exists:
I tried the alternative to ON DUPLICATE KEY UPDATE, REPLACE INTO:
It updates the count, and the vendor_id so it's worse...
The database & data doesn't care if the numbers aren't sequential, only that the values are unique. If you can live with that, I'd use the ON DUPLICATE UPDATE syntax though I admit the behaviour is weird (understandable considering using an INSERT statement).
我想这可能会做到。但这非常违背道教的原则——你确实违背了道教的原则。
可能有更好的解决方案。
I think this might do it. But it's very much against the principles of Daoism - you're really going against the grain.
There is probably a better solution.