简体   繁体   English

SQL通过从同一个表中选择来插入多个值和父ID

[英]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如何通过从同一个表中选择来插入多个值和父 ID

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 MySQL 说:文档 #1093 - 表 'ctg_tbl' 被指定两次,既作为 'INSERT' 的目标,也作为单独的数据源

Your query can be made to work by simply converting it to an INSERT INTO ... SELECT :您的查询可以通过简单地将其转换为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:通过使用ROW 构造函数创建一个包含每行 3 个值的 CTE,您可以在INSERT语句中将其连接到表:

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 .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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