以下是我的数据库架构。
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)
位于from
和to
之间。
我知道可以通过此查询实现。
SELECT *
FROM TABLE
WHERE 4 BETWEEN `from` AND `to`
但是如何在input
15
之间选择价值?
SELECT *
FROM TABLE
WHERE 15 BETWEEN `from` AND `to`
在这种情况下,上述查询无效,因为to
列有null
。
更新
如果columento
可以有任何值,那么它将包含null
。
现在如果输入值为15
,则查询应返回第2行,因为15 is not between 1 and 10 in 1st row
和15
大于11且to
值可以大于11
答案 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)