Table1 product: productname , productID

Table2 alias: product_alias, components, id

Table3 mapping: productId, alias_component_id

INSERT INTO `mapping`(`productId`,`alias_component_id`) VALUES ((SELECT productID FROM product WHERE NAME='abc'), (SELECT id FROM alias WHERE product_alias='xyz'));

The first select would return single value while second select would return multiple values. Basically, for single productId, I want to loop through and insert multiple alias ids. I am getting Subquery returns more than 1 row error

Tried INSERT INTO `mapping`(`alias_component_id`) (SELECT id FROM alias WHERE product_alias='xyz')) but this would leave productID column null.

2

There are 2 answers

1
GMB On

I think you want the INSERT ... SELECT syntax:

INSERT INTO `mapping`(`productId`,`alias_component_id`)  
SELECT p.productID, a.id
FROM product p 
CROSS JOIN alias a 
WHERE p.name = 'abc' AND a.product_alias = 'xyz'
1
astentx On

You don't need to insert with VALUES part, but with SELECT. In this select you join your tables on the logic you need.