我在通过存储过程将数据插入表中时遇到了一些麻烦。请允许我详细解释。
我有一张三张桌子
CREATE TABLE `table_1` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`s_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
`val` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_2` (
`s_id` INT(11) NOT NULL AUTO_INCREMENT,
`t_id` INT(11) NOT NULL,
`p_id` INT(11) NOT NULL,
`d_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_3` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`count` INT(11) NOT NULL,
`created` DATE NOT NULL,
`s_id` VARCHAR(255) NOT NULL,
`t_id` VARCHAR(255) NOT NULL,
`p_id` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
有没有办法使用 select 语句通过存储过程插入第二个表。会有多个数据为Select * from table_1
; 然后会有一个像if(table_1.s_id == table_3.s_id) THEN UPDATE table_3 set count = count +1 ELSE INSERT into table_3
(s_id,t_id.....
虽然我尝试过使用 Cursor 但它只插入一条记录。
这是我使用光标的示例
DECLARE done INT DEFAULT FALSE;
DECLARE curs_count INT(11) DEFAULT 0;
DECLARE v_s_id BIGINT(20) DEFAULT 0;
DECLARE v_t_id BIGINT(20) DEFAULT 0;
DECLARE v_p_id BIGINT(20) DEFAULT 0;
DECLARE v_t_date BIGINT(20) DEFAULT 0;
DECLARE co_s_id BIGINT(20) DEFAULT 0;
DECLARE curs CURSOR FOR
SELECT
a.id,b.s_id,b.t_id,b.created
FROM
table_1 a
INNER JOIN table_2 b ON a.s_id = b.s_id
WHERE
a.val <> '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE curs_id INT(11) DEFAULT 0;
OPEN curs;
SELECT FOUND_ROWS() INTO curs_count;
start_loop: loop
FETCH curs INTO curs_id,v_s_id,v_t_id,v_c_date;
IF done THEN
LEAVE start_loop;
END IF;
SELECT s_id INTO co_s_id FROM table_3;
IF co_s_id>0
THEN
update table_3 SET count = count+1 where s_id = co_s_id;
ELSE
INSERT INTO table_3 (support_id,track_id,track_date,count) VALUES (v_s_id,v_t_id,v_c_date,1);
END IF;
end loop;
CLOSE curs;
谁能帮我解决这个问题?