如何获得一个月内剩余的可用日期进行预订?

时间:2014-04-01 05:09:35

标签: mysql date

我有一个包含以下Schema

的插槽的表
SlotId
FromDate
ToDate

我希望在给定月份的剩余日期可用于广告位预订。

要明确的是,我正在尝试检索除了存储在数据库中的日期(因为已经预订了)的所有日期。

例如,如果记录的FromDate等于2014-04-02ToDate等于2014-04-06,我希望得到以下结果:

2014-04-01
2014-04-07
...
2014-04-30

虽然我使用PHP编写脚本,但我对完成此操作的查询并不感兴趣。

3 个答案:

答案 0 :(得分:1)

所以在mysql中做起来并不容易,但这里应该有用。这会得到任何给定月份中未预订的日期...有关工作示例,请参阅fiddle

SELECT *, union_month.day_date
FROM (
    SELECT 1 AS day_date UNION ALL
    SELECT 2 UNION ALL
    SELECT 3 UNION ALL
    SELECT 4 UNION ALL
    SELECT 5 UNION ALL
    SELECT 6 UNION ALL
    SELECT 7 UNION ALL
    SELECT 8 UNION ALL
    SELECT 9 UNION ALL
    SELECT 10 UNION ALL
    SELECT 11 UNION ALL
    SELECT 12 UNION ALL
    SELECT 13 UNION ALL
    SELECT 14 UNION ALL
    SELECT 15 UNION ALL
    SELECT 16 UNION ALL
    SELECT 17 UNION ALL
    SELECT 18 UNION ALL
    SELECT 19 UNION ALL
    SELECT 20 UNION ALL
    SELECT 21 UNION ALL
    SELECT 22 UNION ALL
    SELECT 23 UNION ALL
    SELECT 24 UNION ALL
    SELECT 25 UNION ALL
    SELECT 26 UNION ALL
    SELECT 27 UNION ALL
    SELECT 28 UNION ALL
    SELECT 29 UNION ALL
    SELECT 30 UNION ALL
    SELECT 31
) AS union_month
LEFT JOIN myTable AS t ON union_month.day_date <> DAY(t.to_date) OR union_month.day_date <> DAY(t.from_date)
WHERE union_month.day_date <= DAY(LAST_DAY(t.to_date))
AND union_month.day_date NOT BETWEEN DAY(t.from_date) AND DAY(t.to_date)
GROUP BY union_month.day_date

对于一个月中的多个日期,将WHERE子句更改为此

WHERE
      union_month.day_date <= DAY(LAST_DAY(t.to_date))
      AND union_month.day_date not BETWEEN (select DAY(from_date) from myTable limit 0,1) AND (select DAY(to_date) from myTable limit 0,1)
      AND union_month.day_date not BETWEEN (select DAY(from_date) from myTable limit 1,1) AND (select DAY(to_date) from myTable limit 1,1)
      AND union_month.day_date not BETWEEN (select DAY(from_date) from myTable limit 2,1) AND (select DAY(to_date) from myTable limit 2,1)
GROUP BY union_month.day_date

为多个日期工作fiddle

答案 1 :(得分:0)

您需要剩余的天数或免费日期吗?

答案 2 :(得分:0)

我试过这个。愿它能帮到你。  您需要在循环中使用此查询。有一些变数。  在示例中,我仅考虑4月份。你可以在几个月内完成。

SELECT distinct * FROM (SELECT DATE_ADD('2014-04-01', INTERVAL t4+t16+t64+t256+t1024 DAY) freedays  FROM 
(SELECT 0 t4    UNION ALL SELECT 1   UNION ALL SELECT 2   UNION ALL SELECT 3  ) t4,
(SELECT 0 t16   UNION ALL SELECT 4   UNION ALL SELECT 8   UNION ALL SELECT 12 ) t16,   
(SELECT 0 t64   UNION ALL SELECT 16  UNION ALL SELECT 32  UNION ALL SELECT 48 ) t64,      
(SELECT 0 t256  UNION ALL SELECT 64  UNION ALL SELECT 128 UNION ALL SELECT 192) t256,     
(SELECT 0 t1024 UNION ALL SELECT 256 UNION ALL SELECT 512 UNION ALL SELECT 768) t1024     
) b 
 WHERE freedays not between (select FrmDate from slotbooking limit 1) and (select ToDate from
  slotbooking limit 1) and freedays < '2014-04-30';