我有2个表,foo
和bar
。 bar
持有foo
的外键,例如:
foo
id | some_data
-: | :--------
1 | a
2 | b
3 | c
bar
id | id_foo | more_data
-: | -----: | :--------
1 | 1 | d
2 | 1 | e
3 | 2 | f
4 | 3 | g
5 | 3 | h
6 | 3 | i
我想动态创建查询以插入到foo
和bar
的其他位置。
对于表foo
,这很容易做到:
SELECT CONCAT('INSERT INTO new_foo (some_data) VALUES (''', f.some_data, ''');') AS 'sql'
FROM foo f;
我得到了预期的结果:
INSERT INTO new_foo (some_data) VALUES ('a');
INSERT INTO new_foo (some_data) VALUES ('b');
INSERT INTO new_foo (some_data) VALUES ('c');
但是,我坚持为包含外键的表生成插入查询。
我以为使用2个UNION
,一个获取最后插入的ID,第二个使用该ID生成对bar
的查询:
SELECT sql
FROM
(
SELECT f.id AS 'id', CONCAT('INSERT INTO new_foo (some_data) VALUES (''', f.some_data, ''');') AS 'sql'
FROM foo f
UNION
SELECT f.id AS 'id', 'SET @last_id = SELECT LAST_INSERT_ID();' AS 'sql' -- Target will be MySQL
FROM foo f
UNION
SELECT b.id_foo AS 'id', CONCAT('INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, ''', b.more_data, ''');') AS 'sql'
FROM bar b
) s
ORDER BY s.id;
这给了我输出:
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'd');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'e');
INSERT INTO new_foo (some_data) VALUES ('a');
SET @last_id = SELECT LAST_INSERT_ID();
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'f');
INSERT INTO new_foo (some_data) VALUES ('b');
SET @last_id = SELECT LAST_INSERT_ID();
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'g');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'h');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'i');
INSERT INTO new_foo (some_data) VALUES ('c');
SET @last_id = SELECT LAST_INSERT_ID();
查询顺序错误。它首先生成对bar
的查询,然后对foo
,然后对LAST_INSERT_ID()
进行查询。
应该是:
INSERT INTO new_foo (some_data) VALUES ('a');
SET @last_id = SELECT LAST_INSERT_ID();
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'd');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'e');
INSERT INTO new_foo (some_data) VALUES ('b');
SET @last_id = SELECT LAST_INSERT_ID();
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'f');
INSERT INTO new_foo (some_data) VALUES ('c');
SET @last_id = SELECT LAST_INSERT_ID();
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'g');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'h');
INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, 'i');
如何确保遵守正确的顺序?我可以处理每个查询在UNION
中的位置,但是不确定是否将保留条目的顺序。
这里是fiddle要玩
您有三行具有相同的ID,并且未指定顺序。您只需添加新列即可指定顺序:
SELECT sql
FROM
(
SELECT f.id AS 'id', -1 AS seq, CONCAT('INSERT INTO new_foo (some_data) VALUES (''', f.some_data, ''');') AS 'sql'
FROM foo f
UNION
SELECT f.id AS 'id', 0 AS seq, 'SET @last_id = SELECT LAST_INSERT_ID();' AS 'sql' -- Target will be MySQL
FROM foo f
UNION
SELECT b.id_foo AS 'id', b.id AS seq, CONCAT('INSERT INTO new_bar (id_foo, more_data) VALUES (@last_id, ''', b.more_data, ''');') AS 'sql'
FROM bar b
) s
ORDER BY s.id, s.seq;