SELECT range of integers in MySQL. Eg. 1,2,3,4,...,n;(SELECT MySQL 中的整数范围.例如.1,2,3,4,...,n;)
问题描述
我需要在 MySQL 中选择整数范围.像这样的
I need to select range of integer in MySQL. Something like this
SELECT RANGE(10,20) AS range;
返回
10, 11, 12, 13, 14, ..., 20
为什么?
我想从尚未注册的范围中选择随机电话号码.这是个主意.
Why?
I would like to select random phone number from range which is not yet registered. This is idea.
SELECT RANGE(100000,999999) AS range FROM phone WHERE phoneNum <> range LIMIT FLOOR(100000 + RAND()*(899999);
推荐答案
您的查询有问题:
- 您不能在 WHERE 子句中使用
range.它是一个别名,只有在 WHERE 子句执行后才会定义. - 即使您可以使用它,使用
<>将一个数字与一组数字进行比较也是没有意义的.一般来说,您可以使用IN(...),但在特定情况下,您应该使用BETWEEN 100000 和 999999并避免使用RANGE代码>功能. - 如果您只想要一个数字,那么限制应该是 1,而不是随机数.通常使用
ORDER BY RAND()来选择随机项目.
- You can't use
rangein the WHERE clause. It is an alias and will only be defined after the WHERE clause is performed. - Even if you could use it, it makes no sense to compare a number with a set of numbers using
<>. In general you could useIN(...), but in you particular case you should useBETWEEN 100000 and 999999and avoid the need for aRANGEfunction. - If you only want one number then the limit should be 1, not something random. Usually to select random items you use
ORDER BY RAND().
尝试使用此查询:
SELECT phoneNum, 100000 as rangeStart, 999999 AS rangeEnd
FROM phone
WHERE phoneNum NOT BETWEEN 100000 AND 999999
ORDER BY RAND()
LIMIT 1
<小时>
如果您想找到一个不在您的表格中的数字并且可用的数字没有接近耗尽(比如分配了不到 80%),那么一个好的方法是生成随机数并检查它们是否被分配,直到您找到一个不是.
If you want to find a number not in your table and the available numbers are not close to depletion (say less than 80% are assigned) a good approach would be to generate random numbers and check if they are assigned until you find one that isn't.
可能存在纯 MySQL 解决方案,但我认为它需要一些扭曲连接、随机连接和模数连接.
这篇关于SELECT MySQL 中的整数范围.例如.1,2,3,4,...,n;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SELECT MySQL 中的整数范围.例如.1,2,3,4,...,n;
基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
