我有下面的表,其中存储了我的产品价格和我的产品的特殊价格数据。我想从下面的数据中得到最便宜的产品。
+------+-------+---------------+-------------------+-----------------+
| id | price | special_price | special_from_date | special_to_date |
+------+-------+---------------+-------------------+-----------------+
| 2647 | 299 | 251 | NULL | NULL |
| 2648 | 299 | 85 | 2017-12-29 | 2018-02-28 |
| 2649 | 299 | NULL | 2017-12-29 | 2018-02-28 |
| 2650 | 299 | 55 | 2017-12-29 | 2018-01-01 |
| 2651 | 299 | 179 | 2017-12-29 | NULL |
+------+-------+---------------+-------------------+-----------------+
这里棘手的部分是,我想检查下面的条件。
price
栏中的最低产品价格。special_price
如果NULL
special_price
,如果special_from_date
和special_to_date
是NULL
,或者当前日期不在范围内special_price
列,如果special_from_date
不是NULL
,而special_from_date
小于当前日期,而special_to_date
为NULL
或大于当前日期。输出如下所示。
+------+-------+---------------+-------------------+-----------------+
| id | price | special_price | special_from_date | special_to_date |
+------+-------+---------------+-------------------+-----------------+
| 2648 | 299 | 85 | 2017-12-29 | 2018-02-28 |
+------+-------+---------------+-------------------+-----------------+
这是我的表模式。
+------------------------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+---------------------+------+-----+---------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| price | decimal(12,4) | YES | | NULL | |
| special_price | decimal(12,4) | YES | | NULL | |
| special_from_date | date | YES | | NULL | |
| special_to_date | date | YES | | NULL | |
+------------------------+---------------------+------+-----+---------+-------+
发布于 2018-02-10 02:39:03
按以下方式获得当前价格:
在下列情况下使用special_price
:
special_price
不为空special_from_date
不为空special_from_date
并不比今天更大special_to_date
为空(打开)special_to_date
不少于当前日期否则使用(默认) price
。
因为如果一方为NULL,则比较将“失败”,因此(2)与(3)是冗余的,因此可以跳过。
为了避免OR-条件,(4)可以表示为coalesce(special_to_date, curdate()) >= curdate()
.
select p.*,
case
when special_price is not null -- 1
and curdate() >= special_from_date -- 2 and 3
and curdate() <= coalesce(special_to_date, curdate()) -- 4
then special_price
else price
end as current_price
from prices p
order by current_price asc
limit 1
演示:http://rextester.com/ETEU48971
请注意,如果要将special_from_date
和special_to_date
包括在范围内,则不太清楚。在这种情况下,它们被包括在内。如果要将它们排除在外,可以使用:
and curdate() > special_from_date
and curdate() < coalesce(special_to_date, curdate() + interval 1 day)
https://dba.stackexchange.com/questions/197478
复制相似问题