简体   繁体   English

如何在MySQL中的INSERT语句中使用SELECT MAX?

[英]How to use SELECT MAX inside an INSERT statement in MySQL?

Short Version: How can I get the maximum value of a column and use the result when adding a row with INSERT INTO statement? 简短版本:如何在使用INSERT INTO语句添加行时获取列的最大值并使用结果?

Long Version: I have read the question: How to use 'select ' in MySQL 'insert' statement and tried to follow the instructions for its answers. 长版:我已经读过这样一个问题: 如何在MySQL'insert'语句中使用'select'并尝试按照说明进行解答。 This is my query: 这是我的查询:

INSERT INTO employee (id, name, state, supervisorId) SELECT MAX(id)+1, 'Dan', state, supervisorId FROM employee WHERE name='Chris';

But I get this error: 但我得到这个错误:

ERROR: 1062: Duplicate entry '7' for key 'PRIMARY'

The reason is that I have another row whose id is 7. Consequently, 原因是我有另一行,其id为7.因此,

MAX(id)

doesn't return the actual maximum value, but a value equal to id of the row containing 'Chris' which is 6. 不返回实际的最大值,而是返回一个值,该值等于包含'Chris'的行的id,即6。

What am I doing wrong? 我究竟做错了什么?

You can fix it by replacing this: 您可以通过替换它来修复它:

MAX(id)+1

with this select query: 使用此选择查询:

(SELECT MAX(id)+1 FROM employee)

Here's the complete query: 这是完整的查询:

INSERT INTO employee (id, name, state, supervisorId) SELECT (SELECT MAX(id)+1 FROM employee), 'Dan', state, supervisorId FROM employee WHERE name='Chris';

Update: 更新:

Although this answer solves the general question about getting the SELECT MAX inside an INSERT query, as @RaymondNijland suggested, it's better to make the most of MySQL auto_increment functionalities. 虽然这个答案解决了关于在INSERT查询中获取SELECT MAX的一般问题,正如@RaymondNijland建议的那样,最好充分利用MySQL的auto_increment功能。 To do so: 为此:

1) Make your primary key column, auto incremented: 1)创建主键列,自动递增:

 ALTER TABLE employee MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;

2) Remove the id from your insert query: 2)从插入查询中删除id:

INSERT INTO employee (name, state, supervisorId) SELECT 'Dan', state, supervisorId FROM employee WHERE name='Chris';

Using manual increment on SQL queries can lead to race conditions. 在SQL查询上使用手动增量可能会导致竞争条件。 You should have the AI (auto increment) constraint when you create your table PK (Primary Key). 创建表PK(主键)时,应该有AI(自动增量)约束。

    CREATE TABLE table_name
    (
    table_id int NOT NULL PRIMARY KEY AUTO INCREMENT,
    ....
    );

If you absolutely have to use manual increment, use SELECT statement. 如果您必须使用手动增量,请使用SELECT语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM