我有一个简单的插入选择,在 _TABLE_A _ 新行中插入 _TABLE_B _ 数据
INSERT INTO _TABLE_A_(_USERNAME_,_ID_)
SELECT _USERNAME_,_ID_
FROM _TABLE_B_
每次在 _TABLE_A _中插入一行时,我想在名为 _TABLE_C _ 的表格中插入一行,并添加当前插入的 _TABLE_C _ ID为 _TABLE_A _ 。
我会试着以另一种方式解释它:
INSERT INTO _TABLE_A_(_USERNAME_,_ID_,_FOREIGN_ID_)
SELECT B._USERNAME_,B._ID_,C._FOREIGN_ID_
FROM _TABLE_B_ AS B
LEFT JOIN _TABLE_C_ AS C
#Insert a row in _TABLE_C_ to retrieve _FOREIGN_ID_...
我正在搜索一个像我这样的 INSERT SELECT 语句的单个最小查询,因为insert select可以循环,我必须循环。
仅供参考: 我在存储过程中。 我还使用带有动态数据的预处理语句,而游标不适合动态数据选择...
答案 0 :(得分:1)
我会首先在_TABLE_C_中执行所有INSERT,然后将其加入INSERT _TABLE_A_以获取相应的外键。
如果那是不可能的,我会使用光标。
Cursor on _TABLE_B_ & Fetch
INSERT _TABLE_C_
INSERT _TABLE_A_ with Foreign_Id = SCOPE_IDENTITY()
Fetch next
答案 1 :(得分:0)
我找到了解决方案。
实施例
BEGIN
DECLARE isDone INT DEFAULT 0;
DECLARE fetchedmemberWhoWillReceiveMailId int;
DECLARE cur1 CURSOR FOR SELECT id FROM memberWhoWillReceiveMail;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET isDone = 1;
SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET @sexe = VAR_sexe;
SET @event = VAR_eventId;
SET @subject = VAR_subject;
SET @body = VAR_body;
SET @to = VAR_to;
SET @from = VAR_from;
SET @region = VAR_region;
SET @departement = VAR_departement;
SET @age = VAR_age;
SET @baseSqlStatement =' CREATE TEMPORARY TABLE memberWhoWillReceiveMail SELECT e.id FROM TABLE_A as e LEFT JOIN TABLE_B AS a on a.member_id = e.id';
SET @whereSqlStatement= 'WHERE e.is_visible = 1 AND e.member_group_id IN (10,11) ';
IF (@region!='') THEN
SET @whereSqlStatement= CONCAT(@whereSqlStatement,' AND region=',@region);
END IF;
IF (@event !=null ) THEN
SET @whereSqlStatement= CONCAT(@whereSqlStatement,' AND m.event_id !=' ,@eventId);
END IF;
IF (@sexe!=null ) THEN
SET @whereSqlStatement= CONCAT(@whereSqlStatement,' AND e.sexe=',@sexe);
END IF;
SET @baseSqlStatement = CONCAT(@baseSqlStatement,@whereSqlStatement);
START TRANSACTION;
PREPARE stmt1 FROM @baseSqlStatement;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
OPEN cur1;
FETCH cur1 INTO fetchedmemberWhoWillReceiveMailId;
WHILE NOT isDone DO
INSERT INTO conversation(created_at,updated_at)VALUES(now(),now());
INSERT INTO message(created_at,updated_at,from, to, uniqueID) VALUES(now(),now(),@from,fetchedmemberWhoWillReceiveMailId,LAST_INSERT_ID() );
FETCH cur1 INTO fetchedmemberWhoWillReceiveMailId; END WHILE; CLOSE cur1;
COMMIT;
DROP TEMPORARY TABLE IF EXISTS memberWhoWillReceiveMail;
END