6

I have lots of products in a product_category table with a category_id of 5. I have added a new category_id of 19. How do I add all products in category 5 to category 19 as well?

I am trying to do something like this:

insert into product_categories( category_id, product_id )
select 19,
   (select product_id
    from product_categories
    where category_id = 5)

but I am getting a sub query returns more than 1 row error.

4 Answers 4

15

try this:

INSERT INTO product_categories (category_id, product_id)
  SELECT 19 AS category_id, product_id 
  FROM product_categories 
  WHERE category_id =5;
Sign up to request clarification or add additional context in comments.

Comments

5

You can do it like this:

INSERT INTO table_a (field, field, timestamp) 
 VALUES (
     (SELECT id FROM tablex WHERE id = :xid LIMIT 1),
     (SELECT id FROM tabley WHERE id = :yid LIMIT 1),
     NOW()
 )

1 Comment

you shouldn't really need the LIMIT's - but handy if you're not using unique row id's
2

Try something like this:

INSERT INTO product_categories( category_id, product_id )
SELECT 19, product_id FROM product_categories WHERE category_id =5

Comments

0

Try with limit

INSERT INTO product_categories( category_id, product_id ) SELECT 19 , (

SELECT product_id FROM product_categories WHERE category_id =5 LIMIT 1)

Comments

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.