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;
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
