1

I wonder if it's possible to make a SQL query between a range that is save in the database as:

1;10

Where 1 is the minimum and 10 the maximum of the range.

For example:

Let's say I have a column 'persons' and the data is saved as above. Now I would like to query all rows where 5 is between the saved range.

Is this possible?

Trekdrop
  • 475
  • 7
  • 27

3 Answers3

3

You could look at this post, which explains how to store tuples in a single MySQL field. It does however complicate things quite a lot.

I don't know much about your actual use case, but I would definitely try to split your min and max values before saving it to the database. Then, simply use a BETWEEN SQL statement

CREATE TABLE  `example` (
  `val` int(10) unsigned NOT NULL,
  `min` int(10) NOT NULL,
  `max` int(10) NOT NULL
);

SELECT * FROM example 
WHERE val BETWEEN min AND max;

I know you specifically said you wanted it saved in one column, but that is simply not what databases are designed to do. They are designed to hold raw data, and a list of values separated by a specific character, no matter how simple and straightforward is processed or formatted data.

Community
  • 1
  • 1
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25
1

SQL Fiddle

DB Schema

create table person
(rng varchar(10));

 insert into person values ('1;10');
 insert into person values ('12;100');

Select Query

SELECT 
rng, cast(SUBSTRING_INDEX(rng, ';', 1) as unsigned) as rangestart,cast(SUBSTRING_INDEX(rng, ';', -1) as unsigned) as rangeend
from person
where 5 between cast(SUBSTRING_INDEX(rng, ';', 1) as unsigned) and cast(SUBSTRING_INDEX(rng, ';', -1) as unsigned)

Output

|  rng | rangestart | rangeend |
|------|------------|----------|
| 1;10 |          1 |       10 |
Maulik Shah
  • 402
  • 1
  • 4
  • 18
  • Nice! This will most likely become very slow for large datasets, since it has to do the substring calculations over and over and over. You will not be able to implement efficient indices. But it is what Lars asked for! – Jorick Spitzen Aug 14 '15 at 08:28
  • Yes. Agreed.For huge data, ideal solution is to have ranges stored in separate columns. But the question does not mention that the table is expected to be heavy. Besides, i trust wisdom of the questioner. – Maulik Shah Aug 14 '15 at 08:34
0

You could split it and check.

DECLARE @YourVariableInBetween INT;
SELECT PersonFullName
FROM PersonTable
WHERE  @YourVariableToCheck BETWEEN CAST((SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(YourRange, ';', 1), ';', -1)) AS UNSIGNED)
AND  CAST((SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(YourRange, ';', 2), ';', -1)) AS UNSIGNED)

Hope this helps

Nathan
  • 1,520
  • 1
  • 12
  • 21