mysql基于条件插入

时间:2014-03-11 09:19:45

标签: mysql insert

我需要根据条件在表中插入一些值。基本上我有两个领域:

从和到

我需要以11为增量插入其范围内的值。

假设以下

From = 79090200 至= 79090233

因此将保存以下值: 79090200 79090211 79090222 79090233

我还是个新手,所以任何帮助都意味着很多。

2 个答案:

答案 0 :(得分:0)

您可以使用UNION生成一系列数字,并根据该数字插入。这样的事情: -

INSERT INTO SomeTable (SomeNumeric)
SELECT 79090200 + ((Units.i + Tens.i * 10 + Hundreds.i * 100) * 11) AS SomeNumber
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Hundreds
HAVING SomeNumber BETWEEEN 79090200 AND 79090233

答案 1 :(得分:0)

您可以使用以下存储过程将这些值存储在表

DELIMITER $$
USE test$$

DROP PROCEDURE IF EXISTS `sp_increment`$$

CREATE DEFINER = `root`@`localhost` PROCEDURE `test`.`sp_increment`()

    BEGIN


DECLARE start_val INT;
DECLARE end_val INT;

SET start_val=79090200;
SET end_val=79090233;

WHILE start_val <= end_val DO
    INSERT INTO mytable (mycolumn) VALUES(start_val);
    SET start_val = start_val + 11;
END WHILE;


    END$$

DELIMITER ;

您可以使用以下程序从表中获取值 -

DELIMITER $$
USE test$$

DROP PROCEDURE IF EXISTS `sp_increment`$$

CREATE DEFINER = `root`@`localhost` PROCEDURE `test`.`sp_increment`()

    BEGIN


 DECLARE s_val INT;
 DECLARE e_val INT;

SELECT st_val, end_val INTO @start_val, @end_val FROM my_val;

 SET s_val=@start_val;
 SET e_val=@end_val;

WHILE s_val <= e_val DO
    INSERT INTO increment_tbl VALUES(s_val);
    SET s_val = s_val + 11;
END WHILE;


    END$$

DELIMITER ;