如何从MySQL查询生成一系列连续数字(每行一个),以便我可以将它们插入表中?
例如:
nr 1 2 3 4 5
我想只使用MySQL(不是PHP或其他语言).
这是一种基于集合而无循环的方法.这也可以作为重复使用的视图.该示例显示了从0到999的序列的生成,但是当然,可以对其进行修改以适应.
INSERT INTO myTable ( nr ) SELECT SEQ.SeqValue FROM ( SELECT (HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue FROM ( SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue UNION ALL SELECT 2 SeqValue UNION ALL SELECT 3 SeqValue UNION ALL SELECT 4 SeqValue UNION ALL SELECT 5 SeqValue UNION ALL SELECT 6 SeqValue UNION ALL SELECT 7 SeqValue UNION ALL SELECT 8 SeqValue UNION ALL SELECT 9 SeqValue ) ONES CROSS JOIN ( SELECT 0 SeqValue UNION ALL SELECT 10 SeqValue UNION ALL SELECT 20 SeqValue UNION ALL SELECT 30 SeqValue UNION ALL SELECT 40 SeqValue UNION ALL SELECT 50 SeqValue UNION ALL SELECT 60 SeqValue UNION ALL SELECT 70 SeqValue UNION ALL SELECT 80 SeqValue UNION ALL SELECT 90 SeqValue ) TENS CROSS JOIN ( SELECT 0 SeqValue UNION ALL SELECT 100 SeqValue UNION ALL SELECT 200 SeqValue UNION ALL SELECT 300 SeqValue UNION ALL SELECT 400 SeqValue UNION ALL SELECT 500 SeqValue UNION ALL SELECT 600 SeqValue UNION ALL SELECT 700 SeqValue UNION ALL SELECT 800 SeqValue UNION ALL SELECT 900 SeqValue ) HUNDREDS ) SEQ
这是匹兹堡DBA解决方案的硬件工程师版本:
SELECT (TWO_1.SeqValue + TWO_2.SeqValue + TWO_4.SeqValue + TWO_8.SeqValue + TWO_16.SeqValue) SeqValue FROM (SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue) TWO_1 CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 2 SeqValue) TWO_2 CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 4 SeqValue) TWO_4 CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 8 SeqValue) TWO_8 CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 16 SeqValue) TWO_16;
如果您需要表中的记录并且希望避免并发问题,请按照以下步骤操作.
首先,您创建一个用于存储记录的表
CREATE TABLE `incr` ( `Id` int(11) NOT NULL auto_increment, PRIMARY KEY (`Id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
其次创建一个这样的存储过程:
DELIMITER ;; CREATE PROCEDURE dowhile() BEGIN DECLARE v1 INT DEFAULT 5; WHILE v1 > 0 DO INSERT incr VALUES (NULL); SET v1 = v1 - 1; END WHILE; END;; DELIMITER ;
最后致电SP:
CALL dowhile(); SELECT * FROM incr;
结果
Id 1 2 3 4 5
假设您要在表格中插入数字1到100.只要你有一些其他表至少包含很多行(与表的内容无关),那么这是我首选的方法:
INSERT INTO pivot100 SELECT @ROW := @ROW + 1 AS ROW FROM someOtherTable t join (SELECT @ROW := 0) t2 LIMIT 100 ;
想要一个以1以外的东西开头的范围?只需更改@ROW在连接上设置的内容即可.
DECLARE i INT DEFAULT 0; WHILE i < 6 DO /* insert into table... */ SET i = i + 1; END WHILE;
大家都明白,这是相当hacky所以要小心使用
SELECT id % 12 + 1 as one_to_twelve FROM any_large_table group by one_to_twelve