I am using the JPA with JPQL queries to retrieve data from a MySQL DB. But my problem is rather logical than language specific (I think)...
I would like to SELECT all entries of a table WHERE one column is in BETWEEN a list of ranges.
For example:
SELECT x FROM myTable
WHERE x BETWEEN 2 AND 5
OR x BETWEEN 7 AND 9
While the ranges (2-5, 7-9) come from another table:
RANGES ex: id | from | to
–––––––––– –––––––––––––––
id: INT 1| 2| 5
from: INT 2| 7| 9
to: INT 3| 9| 15
4| 17| null
My problem a)
is, that the Ranges list is dynamic and could be either only one range, like
x BETWEEN 2 AND 5
or multiple ranges like
x BETWEEN 2 AND 5 OR x BETWEEN 7 AND 9 OR x BETWEEN ....
My problem b)
is, that the Ranges could also be open like
x >= 17
My problem c)
is, that there are other WHERE conditions, limiting the results. Some of those WHERE conditions are more "limiting" than the BETWEEN conditions. So they come first, to make the whole query faster. Let's say for example
... WHERE x%2=0 AND x BETWEEN 2 AND 5
For c) I thought about sub-queries, for example:
SELECT x FROM myTable
WHERE x IN (
SELECT x FROM myTable
WHERE x BETWEEN 2 AND 5
OR x BETWEEN 7 AND 9
)
AND y .. something something
The "good" thing is, I use Java and the JPA to create my queries, so I could create the queries dynamically. But before abusing String concatenation to dynamically create SQL queries, I was hoping to find a cleaner solution in pure SQL (or even better in JPQL)