PHP和MySQL:将月份和日期与动态年份进行比较


PHP and MySQL: Comparing month and day with dynamic year

我正在开发的应用程序遇到了一些问题,希望能得到一些指导。

我有一个简单的预订系统:每件商品都有一个标准价格,但有时价格会发生变化。

例如:

  • 标准价格为100/天

  • 从每年的Oct. 1stFeb. 1st,价格为80/天

  • 从每年的Jun. 1stAug. 31st,价格为120/天

  • […]多达6种不同的价格变化(季节)

因为这是每年都会发生的事情,我只需要月份和日期,但我不知道如何将这些值存储在数据库中。我想有两个字段,一个表示月份,另一个表示日期,其中包含数值(01-12表示月份,01-31表示日期)。这些值是由用户自己设置的,它们是相对于项目本身的,并不是每个人都固定的。

问题是,当有人预订时,我需要检查价格是否需要更改,但我不知道如何建立查询来检查这一点。最糟糕的是,在一个预订期内,价格可能有多个值。

按照上面的例子,如果我要预订从Sep. 1st (current year)Jul. 1st (next year)的商品,价格如下:

  • 100/天Sep. 1stSep. 30th

  • 80/天Oct. 1stFeb. 1st

  • 100/天来自Feb. 2nd to May 31st

  • 120/天Jun. 1stJul. 1st

有没有任何方法可以检查这些案例,而不必每天循环并对照数据库检查匹配情况?

感谢

您可以在检查日期时使用MySQL date_format函数。

例如:

select date_format('2016-05-18', '%m%d');
+-----------------------------------+
| date_format('2016-05-18', '%m%d') |
+-----------------------------------+
| 0518                              |
+-----------------------------------+
1 row in set (0,01 sec)

所以,你可以用简单的间隔来检查:今天是0518,它介于2月2日和5月31日之间:

0202<=0518<=0531

完整示例:

desc mytable;
+-----------+---------+------+-----+---------+-------+
| Field     | Type    | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| date_from | char(4) | YES  |     | NULL    |       |
| date_to   | char(4) | YES  |     | NULL    |       |
| price     | int(11) | YES  |     | NULL    |       |
+-----------+---------+------+-----+---------+-------+
3 rows in set (0,00 sec)
select * from mytable;
+-----------+---------+-------+
| date_from | date_to | price |
+-----------+---------+-------+
| 0901      | 0930    |   100 |
| 1001      | 0201    |    80 |
| 0202      | 0531    |   100 |
| 0601      | 0701    |   120 |
+-----------+---------+-------+
4 rows in set (0,00 sec)

示例查询:

select price, date_from, date_to from mytable where date_format(now(), '%m%d') between date_from and date_to;
+-------+-----------+---------+
| price | date_from | date_to |
+-------+-----------+---------+
|   100 | 0202      | 0531    |
+-------+-----------+---------+
1 row in set (0,01 sec)

编辑

阅读您对@FelipeDuarte回答的评论。。。从2001年10月1日到2001年2月1日,我们需要考虑新的一年。。。

你可以通过将周期分成两个来作弊:10/01到12/31和01/01到02/01

我不知道你的数据库表,但我认为你可以这样做:

  1. 获取您的经期,iniDay,iniMonth,endDay,endMonth
  2. 您的表需要有以下字段:ini_day、ini_month、ini_dymonth、end_day、end_month,end_dymont、price_day
  3. SELECT * from table WHERE iniDay >= booking_ini_day AND iniMonth >= booking_ini_month -- get initial period AND iniDay <= booking_end_day AND iniMonth <= booking_end_month UNION ALL SELECT * from table WHERE iniDay <= booking_ini_day AND iniMonth <= booking_ini_month -- get middle periods AND endDay >= booking_end_day AND endMonth >= booking_end_month UNION ALL SELECT * from table WHERE endDay >= booking_ini_day AND endMonth >= booking_ini_month AND endDay <= booking_end_day AND endMonth <= booking_end_month -- get end period
  4. 计算结果查询中每个期间/行的天数并显示给用户

您将"复制"数据库信息,如天、月和日,但这是为了获得更好的性能。