Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

sql - How do you SELECT MAX() inside an INSERT in MYSQL to automatically increase the customerNumber

I have been trying to add a new row in the table which will add the following but then automatically increment the customerNumber by one to a new value from the table. I have tried it out with variables and it worked but I need to do this query in one operation.

INSERT INTO customers (customerNumber,customerName, contactLastName, contactFirstName, phone, addressLine1, addressLine2, city, state, postalCode, country)
VALUES ((SELECT MAX(customerNumber)+1 FROM customers),'Detectives Inc.', 'Holmes', 'Sherlock', '2743824490', '221B Baker Street', 'Apt 2', 'London', 'LL', '50876', 'England');

This is what I have been trying but I get an error "You can't specify target table 'customers' for update in FROM clause"

EDIT

I resolved the issue by doing the following query

INSERT INTO customers (customerNumber,customerName, contactLastName, contactFirstName, phone, addressLine1, addressLine2, city, state, postalCode, country) SELECT MAX(customerNumber)+1 ,'Detectives Inc.', 'Holmes', 'Sherlock', '2743824490', '221B Baker Street', 'Apt 2', 'London', 'LL', '50876', 'England' FROM customers;

question from:https://stackoverflow.com/questions/65838728/how-do-you-select-max-inside-an-insert-in-mysql-to-automatically-increase-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use sub-query and try as follows:

...
VALUES ((SELECT MAX(customerNumber)+1 from (select customernumber FROM customers) t),'Detectives Inc.'
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...