我坚持如何从前一个插入语句中获得递增的id和max,min,sum或count。
任何人都可以建议我如何以简单的方式做到这一点吗?
CREATE PROCEDURE INSERTRECORD()
BEGIN
INSERT INTO tb_normalized_data_20110615
SELECT * FROM tb_normalized_data WHERE
date_added BETWEEN '2011-06-15 01:10:00' and '2011-06-15 01:19:59'
-- Stuck here how to get the value for(x_min_id, x_max_id, x_min_date,
-- x_max_date) from the statement above without querying again?
INSERT INTO tb_backup_tracker(min_id, max_id, min_date, max_date)
VALUES(x_min_id, x_max_id, x_min_date, x_max_date);
END;
答案 0 :(得分:1)
我认为你正在寻找一个cursor。基本上,这是它的工作方式:
DECLARE cur CURSOR FOR SELECT * FROM tb_normalized_data WHERE
date_added BETWEEN '2011-06-15 01:10:00' and '2011-06-15 01:19:59';
DECLARE ID INT;
DECLARE DT DATE;/* Declare all of your columns */
DECLARE MIN_ID INT;
DECLARE MAX_ID INT;
DECLARE MIN_DATE DATE;
DECLARE MAX_DATE DATE;
-- add your other columns here...
BEGIN
OPEN cur;
read_loop: LOOP
FETCH cur INTO ID, DT /* Fetch into all of your columns */;
IF ID < MIN_ID THEN
SET @MIN_ID = ID;
IF ID > MAX_ID THEN
SET @MAX_ID = ID;
END IF;
INSERT INTO tb_normalized_data_20110615 (ID, DATE_ADDED
/*, rest of your columns*/ ) VALUES( /* columns */ );
END LOOP;
INSERT INTO tb_backup_tracker(min_id, max_id, min_date, max_date)
VALUES(min_id, max_id, min_date, max_date);
CLOSE cur;
答案 1 :(得分:0)
使用光标循环遍历数据并在光标循环内部插入和以跟踪最小/最大值,无论您需要什么。
此外,您的代码很脆弱:避免使用模式INSERT INTO TABLE SELECT * FROM ...
;如果第二个表添加了一个SQL,那么SQL将会中断。最好明确命名列。
如果您需要光标帮助,请发布。