Question: Need a generic sql query for joins that can run on mysql, postgres and other major DBs

I have a table named autumn4.ip , I have `three columns: id,start,end (all ints).`

How do I make a join so that I make use of BUT not by BETWEEN but by JOINS.

like pseudo:

```
select * FROM autumn.ip WHERE :number-constant >= start ORDER BY start DESC LIMIT 1; +

select * FROM autumn.ip WHERE :number-constant <= end ORDER BY start ASC LIMIT 1;

```

how to some one join the above two queries to get one row of data that would be equivalent to

```
SELECT * FROM autumn4.ip WHERE :number-constant BETWEEN START AND END LIMIT 1;

```

Just dont ask my why I am doing it :)
but I know you woudl so:

I am trying to accomplish is to use 2 indexes, start and end. if i use BETWEEN and/or a composite index of start,end. Only start index is used and not the end. now please dont tell me that I am wrong. I just want it that way. I have done alot of research on this

if i do create single indexes for both start and end, only one is used. give me a query in which both are used

Answer: 
If you need to do this multi-level lookup very often, this helper method can be useful:

```py
def multi_get(dict_obj, *attrs, default=None):
    result = dict_obj
    for attr in attrs:
        if attr not in result:
            return default
        result = result[attr]
    return result

```

To use it, just call it like:

```py
x = multi_get(data, 'a', 'b', 'c', default=False)

```
There's two solutions:

### Return a default value with defaultdict

You can use a [`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict), and intstantiate an inner level with another `defaultdict`. Then, if the key is missing, it'll return an empty dict without throwing errors:

```
from collections import defaultdict

>>> d = defaultdict(lambda: defaultdict(dict))
>>> d['a']['b']
{}

```

If you need more levels, you just have to chain many `lambda`.

Partial reference: [Multiple levels of 'collection.defaultdict' in Python](https://stackoverflow.com/questions/2600790/multiple-levels-of-collection-defaultdict-in-python)

### Handle the missing key with a try/except

Another way is to surronding the dict access with `try`/`except` block and manage the missing key through the `KeyError` exception (stop the program, return a default value, etc.)

```
try:
    x = data[a][b][c]
    # same code of your if statement
except KeyError:
    # stuff you do in your else

```