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 Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
