SELECT range of integers in MySQL. Eg. 1,2,3,4,…,n;

早过忘川 提交于 2020-01-12 14:00:04

问题


I need to select range of integer in MySQL. Something like this

SELECT RANGE(10,20) AS range;

returns

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);


回答1:


Problems with your query:

  1. You can't use range in the WHERE clause. It is an alias and will only be defined after the WHERE clause is performed.
  2. Even if you could use it, it makes no sense to compare a number with a set of numbers using <>. In general you could use IN(...), but in you particular case you should use BETWEEN 100000 and 999999 and avoid the need for a RANGE function.
  3. 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().

Try using this query:

SELECT phoneNum, 100000 as rangeStart, 999999 AS rangeEnd
FROM phone
WHERE phoneNum NOT BETWEEN 100000 AND 999999
ORDER BY RAND()
LIMIT 1

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.

A pure MySQL solution may exists but I think it needs some twisted joins, random and modulus.




回答2:


An alternative:

First of all create a table with just numbers that has all the numbers from 1 to MAX_NUM.

Then use this query:

SELECT n.id as newNumber
FROM numbers AS n
LEFT JOIN phone AS p
    ON p.phoneNum = n.id
WHERE 
    p.phoneNum IS NULL AND
    n.id BETWEEN lowerLimit AND upperLIMIT    
ORDER BY RAND()
LIMIT 1

This way you can also get multiple number relatively fast by changing the limit value.



来源:https://stackoverflow.com/questions/4386425/select-range-of-integers-in-mysql-eg-1-2-3-4-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!