MySQL中的数字序列 [英] Number Sequence in MySQL

查看:91
本文介绍了MySQL中的数字序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果我想要0到9(含)之间的序列,我会使用xrange(0,10).有没有办法可以在MySQL中做到这一点?

In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL?

推荐答案

由于没有诸如xrange之类的东西,因此可以使用存储有整数的另一张表(如先前回答的那样),或者只是制作一个存储过程来执行工作:

Since there is no such thing as xrange, one could use a separate table stored with integer (as previously answered), or just make a stored procedure to do the job:

DROP PROCEDURE IF EXISTS xrange;
DELIMITER //
CREATE PROCEDURE xrange(x INT, y INT)
BEGIN
  DECLARE i INT DEFAULT x;
  CREATE TEMPORARY TABLE xrange_tmp (c1 INT);
  WHILE i < y DO
    INSERT INTO xrange_tmp VALUES (i);
    SET i = i + 1;
  END WHILE;
END;
//

用法:

CALL xrange(-2,10);
SELECT c1 FROM xrange_tmp;
DROP TABLE xrange_tmp;

上面的内容显然比用整数创建一个就绪表要慢.不过,它更灵活.

The above is obviously going to be slower than creating a ready table with integers. It's more flexible though.

这篇关于MySQL中的数字序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆