检查两列之间的输入值

时间:2013-01-17 06:58:08

标签: mysql sql select

以下是我的数据库架构。

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`

但是如何在input 15之间选择价值?

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

在这种情况下,上述查询无效,因为to列有null

更新

如果columen to可以有任何值,那么它将包含null

现在如果输入值为15,则查询应返回第2行,因为15 is not between 1 and 10 in 1st row15大于11且to值可以大于11

3 个答案:

答案 0 :(得分:9)

SELECT *
FROM   TABLE
WHERE  15 BETWEEN coalesce(`from`,15) AND coalesce(`to`,15);

答案 1 :(得分:0)

使用布尔组合

select *
    from table
    where (to is not null and 15 between from and to)
        or (to is null and 15 >= from)

答案 2 :(得分:0)

SELECT *
FROM   TABLE
WHERE  15 BETWEEN `from` AND IF_NULL(`to`,15)