0

I have a table called productcategory I want to insert two static values to the columns category_name and parent_id and need to insert column sort_order with a value generated from inner select query

INSERT INTO productcategory(category_name,parent_id,sort_order) 
values('Flowers',0,(select MAX(sort_order)+1 from productcategory where parent_id=0))

SQL query not working
Thanks in Advance

2
  • Is the actual error message classified? I cannot think of any other reason for not sharing it with us. My guess is that you cannot select from the table in a subquery which you try to modify. Commented Sep 2, 2016 at 5:23
  • Possible duplicate of Select from same table as an Insert or Update Commented Sep 2, 2016 at 7:40

3 Answers 3

1

It should work like this:

INSERT INTO productcategory(category_name,parent_id,sort_order)
SELECT 'Flowers', 0, MAX(sort_order)+1
FROM   productcategory
WHERE  parent_id = 0
Sign up to request clarification or add additional context in comments.

1 Comment

Glad it works, so please accept the answer so others can see this question is solved :)
1

You can't select from the table in a sub query which you try to update or insert.

As per my knowledge this can be achieved by using SET method like below.

SELECT @maxSortOrder := IFNULL(MAX(sort_order),0)+1 FROM productcategory WHERE parent_id=0;
INSERT INTO productcategory(category_name,parent_id,sort_order) VALUES('Flowers',0,@maxSortOrder);

This may help you.

Comments

0

Now try this:

CREATE TABLE dupproduct AS (SELECT * FROM productcategory);

INSERT INTO productcategory (
  category_name,
  parent_id,
  sort_order
) 
VALUES
  (
    'Flowers',
    0,
    (SELECT 
      MAX(sort_order) + 1 
    FROM
      dupproduct 
    WHERE parent_id = 0)
  );


  DROP TABLE dupproduct;

1 Comment

Do you seriously suggest to copy the entire table to make the query work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.