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);
To generate a range of numbers in MySQL, you can use stored procedure. Firstly, we need to create a table. After that, we will create a stored procedure that generates a range of number from 10 to 1. After that we need to call the stored procedure that fills a range of numbers in the table.
You have to use the LIMIT clause in the SELECT query. MySQL allows you to set two parameters for the clause, the offset (first parameter) and the number of rows to fetch (second parameter). SELECT * FROM `ABC` LIMIT 0, 100 SELECT * FROM `ABC` LIMIT 100, 100 SELECT * FROM `ABC` LIMIT 200, 100 -- etc...
The range access method uses a single index to retrieve a subset of table rows that are contained within one or several index value intervals. It can be used for a single-part or multiple-part index.
BETWEEN clause is inclusive, for example, suppose there are 1,2,3,4,5,6 numbers. If you want to display numbers from 2 to 6 inclusively, then using BETWEEN the numbers 2 and 6 will also get displayed.
Problems with your query:
range
in the WHERE clause. It is an alias and will only be defined after the WHERE clause is performed.<>
. 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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With