3

下面是我的数据库架构。

id   from  to    value
1    1     10    5
2    11    NULL  10   -- I have stored 'NULL' for any value GREATER THAN 11

现在我必须选择和之间的value位置。input like (4)fromto

我知道可以通过这个查询来实现。

SELECT *
FROM   TABLE
WHERE  4 BETWEEN `from` AND `to`

但是如何选择价值input15

SELECT *
FROM   TABLE
WHERE  15 BETWEEN `from` AND `to`

在这种情况下,上面的查询将不起作用,因为to列有null.

更新

如果它可以有任何值,列to将包含。null

现在如果输入值为15,则查询应返回第二行,因为15 is not between 1 and 10 in 1st rowand15大于 11 并且tovalue 可以是大于 11 的任何值。

4

3 回答 3

9
SELECT *
FROM   TABLE
WHERE  15 BETWEEN coalesce(`from`,15) AND coalesce(`to`,15);
于 2013-01-17T07:14:29.580 回答
0

使用布尔组合

select *
    from table
    where (to is not null and 15 between from and to)
        or (to is null and 15 >= from)
于 2013-01-17T07:03:38.150 回答
0
SELECT *
FROM   TABLE
WHERE  15 BETWEEN `from` AND IF_NULL(`to`,15)
于 2013-01-17T07:21:23.333 回答