简体   繁体   中英

SQL insert multiple values and parent id by selecting from same table

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

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';

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM