我是sql的新手,我需要在两次查询之间使用DB表获取数据。我尝试过但无法获得所需的结果。下面是我的表结构
编辑: 我正在尝试按照查询中指定的时间获取利率。 如果我将周期指定为6,则利率应为3,即使指定11的利率也应仅为3。
假设期间为13,则费率应为4。
interest table ---------------------------------- id | year | min | max | interest | ---------------------------------- 1 | 2019 | 6 | 11 | 3 | 1 | 2019 | 12 | 0 | 4 |
下面的查询将向我返回正确的利率。
SELECT * FROM interest WHERE 6 BETWEEN min AND max AND year=2019
但是当我传递值5时,它返回null,但仍然要求结果为 “利率= 3” 。
而且当我超过13岁时,我应该得到的结果为 “利率= 4” 但我返回null。
我尝试了 * <=和> = * ,即使那没有用。 我要去哪里错了..
答案 0 :(得分:0)
如果您无法“固定”利息表,则可以通过计算最小最小值将其重置为0以及类似的最大最小值来对其进行调整
所以给了你数据
select i.*,
case when min = (select min(min) from interest) then 0 else min end as minmin,
case when min = (select max(min) from interest) then 999 else max end as maxmax
from interest i
returns
+------+------+------+------+----------+--------+--------+
| id | year | min | max | interest | minmin | maxmax |
+------+------+------+------+----------+--------+--------+
| 1 | 2019 | 6 | 11 | 3 | 0 | 11 |
| 1 | 2019 | 12 | 0 | 4 | 12 | 999 |
+------+------+------+------+----------+--------+--------+
2 rows in set (0.00 sec)
然后可以用来检查您的输入值
select s.*
from
(
select i.*,
case when min = (select min(min) from interest) then 0 else min end as minmin,
case when min = (select max(min) from interest) then 999 else max end as maxmax
from interest i
) s
where 5 between minmin and maxmax and year = 2019;
+------+------+------+------+----------+--------+--------+
| id | year | min | max | interest | minmin | maxmax |
+------+------+------+------+----------+--------+--------+
| 1 | 2019 | 6 | 11 | 3 | 0 | 11 |
+------+------+------+------+----------+--------+--------+
1 row in set (0.00 sec)