Insert and set value with max()+1 problems(使用 max()+1 问题插入和设置值)
问题描述
我正在尝试插入一个新行并使用 max()+1 设置 customer_id.这样做的原因是该表已经在另一列名为 id 的列上有一个 auto_increatment,并且该表将有多个具有相同 customer_id 的行.
I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the table will have multiple rows with the same customer_id.
有了这个:
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id ) FROM customers) +1, 'jim', 'sock')
...我不断收到以下错误:
...I keep getting the following error:
#1093 - You can't specify target table 'customers' for update in FROM clause
另外,我如何阻止同时添加 2 个不同的客户并且没有相同的 customer_id?
Also how would I stop 2 different customers being added at the same time and not having the same customer_id?
推荐答案
正确,不能在同一个查询的同一个表中修改和选择.您必须在两个单独的查询中执行上述操作.
Correct, you can not modify and select from the same table in the same query. You would have to perform the above in two separate queries.
最好的方法是使用事务,但如果您不使用 innodb 表,那么下一个最好的方法是 锁定表,然后执行查询.所以:
The best way is to use a transaction but if your not using innodb tables then next best is locking the tables and then performing your queries. So:
Lock tables customers write;
$max = SELECT MAX( customer_id ) FROM customers;
获取最大id然后执行插入
Grab the max id and then perform the insert
INSERT INTO customers( customer_id, firstname, surname )
VALUES ($max+1 , 'jim', 'sock')
unlock tables;
这篇关于使用 max()+1 问题插入和设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 max()+1 问题插入和设置值


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01