Home > front end >  SQL insert multiple values and parent id by selecting from same table
SQL insert multiple values and parent id by selecting from same table

Time:10-31

How do I insert multiple values and parent id by selecting from same table

I tried below and getting an error

INSERT IGNORE INTO ctg_tbl (`ctg_name`,`ctg_img`,`ctg_parent_id`)
VALUES 
('Gravy', 'GravyImg', (SELECT id FROM ctg_tbl WHERE ctg_name='Foods')),
('Curry', 'CurryImg', (SELECT id FROM ctg_tbl WHERE ctg_name='Foods')),
('Ball', 'BallImg', (SELECT id FROM ctg_tbl WHERE ctg_name='Games'))

MySQL said: Documentation #1093 - Table 'ctg_tbl' is specified twice, both as a target for 'INSERT' and as a separate source for data

CodePudding user response:

Your query can be made to work by simply converting it to an INSERT INTO ... SELECT:

INSERT IGNORE INTO ctg_tbl (ctg_name, ctg_img, ctg_parent_id)
SELECT 'Gravy', 'GravyImg', id FROM ctg_tbl WHERE ctg_name = 'Foods'
UNION ALL
SELECT 'Curry', 'CurryImg', id FROM ctg_tbl WHERE ctg_name = 'Foods'
UNION ALL
SELECT 'Ball', 'BallImg', id FROM ctg_tbl WHERE ctg_name = 'Games';

CodePudding user response:

Try this one

    DECLARE @FoodID INT = (SELECT TOP (1) id FROM ctg_tbl WHERE ctg_name = 'Foods')
    DECLARE @GameID INT = (SELECT TOP (1) id FROM ctg_tbl WHERE ctg_name = 'Games')

    INSERT IGNORE INTO ctg_tbl (`ctg_name`,`ctg_img`,`ctg_parent_id`)
    VALUES 
    ('Gravy', 'GravyImg', @FoodID),
    ('Curry', 'CurryImg', @FoodID),
    ('Ball', 'BallImg', @GameID)

CodePudding user response:

Create a CTE that contains the 3 values that you have for each row, by using the ROW constructor, which you can join to the table in the INSERT statement:

INSERT IGNORE INTO ctg_tbl (ctg_name , ctg_img , ctg_parent_id ) 
WITH cte(ctg_name , ctg_img , ctg_parent_name) AS (
  VALUES 
  ROW('Gravy', 'GravyImg', 'Foods'),
  ROW('Curry', 'CurryImg', 'Foods'),
  ROW('Ball', 'BallImg', 'Games')
)
SELECT c.ctg_name, c.ctg_img, t.id
FROM cte c INNER JOIN ctg_tbl t
ON t.ctg_name = ctg_parent_name;

See the demo.

  • Related