我想根据先前查询的多行结果的结果更新第三个表。
示例以显示我的意思
SET @NAME1='name1';
SET @NAME21='name21';
SET @NAME22='name22';
SET @ID1 = (SELECT ID1 FROM TABLE1 WHERE NAME=@NAME1);
SET @ID21 = (SELECT ID2 FROM TABLE2 WHERE NAME=@NAME21);
SET @ID22 = (SELECT ID2 FROM TABLE2 WHERE NAME=@NAME22);
INSERT INTO TABLE3 ('ID1', 'ID2')
VALUES(@ID1, @ID21);
INSERT INTO TABLE3 ('ID1', 'ID2')
VALUES(@ID1, @ID22);
到目前为止这么容易。但是,如果TABLE1返回多行结果,我该如何处理呢? 我必须在myBatis“MIGRATE”-script中执行此操作;没有任何计划支持;只是简单的SQL。数据库是MySQL。
答案 0 :(得分:0)
我看到的唯一方法是使用存储过程
DROP PROCEDURE IF EXISTS UpdateWithSuppliedName;
DELIMITER $$
CREATE PROCEDURE UpdateWithSuppliedName( IN aName VARCHAR(20) )
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id INT;
DECLARE myCursor CURSOR FOR SELECT t1id FROM table1 WHERE NAME=aName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Fail if supplied name is not defined
SET @size = (SELECT count(*) from table1 WHERE NAME=aName);
IF @size = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = "Supplied name does not exist in table1";
END IF;
-- Fail if expected name2 is not there in table2
SET @size = (SELECT count(*) from table2 WHERE NAME="NAME21");
IF @size = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = "The name 'NAME21' does not exist in table2";
END IF;
-- Fail if expected name2 is not there in table2
SET @size = (SELECT count(*) from table2 WHERE NAME="NAME22");
IF @size = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = "The name 'NAME22' does not exist in table2";
END IF;
SET @id21 = (SELECT t2id from table2 WHERE NAME="NAME21");
SET @id22 = (SELECT t2id from table2 WHERE NAME="NAME22");
OPEN myCursor;
read_loop: LOOP
FETCH myCursor INTO id;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO table3 (t1id, t2id) VALUES (id, @id21);
INSERT INTO table3 (t1id, t2id) VALUES (id, @id22);
END LOOP;
CLOSE myCursor;
END $$
DELIMITER ;
call UpdateWithSuppliedName("NAME11");
-- cleanup
DROP PROCEDURE IF EXISTS UpdateWithSuppliedName;