用mysql查找日期空白

前端之家收集整理的这篇文章主要介绍了用mysql查找日期空白前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想提取具有空的bookingId的记录并获得最多未预订的天数(从第一个免费日).预期结果应该是:

  1. id = 1,2013-08-03,7 days free
  2. id = 1,2013-08-24,7 days free
  3. id = 2,2013-08-07,10 days free
  4. id = 2,7 days free

最好的事情是,如果我还可以查询免费时间段:例如查询1,2,3,4,5,6,7..14 ..免费日.这是我的源数据的一个示例:

  1. id bookingDate bookingId
  2. --------------------------------
  3. 1 2013-08-03 0
  4. 1 2013-08-04 0
  5. 1 2013-08-05 0
  6. 1 2013-08-06 0
  7. 1 2013-08-07 0
  8. 1 2013-08-08 0
  9. 1 2013-08-09 0
  10. 1 2013-08-10 112
  11. 1 2013-08-11 112
  12. 1 2013-08-12 112
  13. 1 2013-08-13 112
  14. 1 2013-08-14 112
  15. 1 2013-08-15 112
  16. 1 2013-08-16 112
  17. 1 2013-08-17 112
  18. 1 2013-08-18 112
  19. 1 2013-08-19 112
  20. 1 2013-08-20 112
  21. 1 2013-08-21 112
  22. 1 2013-08-22 112
  23. 1 2013-08-23 112
  24. 1 2013-08-24 0
  25. 1 2013-08-25 0
  26. 1 2013-08-26 0
  27. 1 2013-08-27 0
  28. 1 2013-08-28 0
  29. 1 2013-08-29 0
  30. 1 2013-08-30 0
  31. 1 2013-08-31 0
  32. 2 2013-08-03 78
  33. 2 2013-08-04 78
  34. 2 2013-08-05 78
  35. 2 2013-08-06 78
  36. 2 2013-08-07 0
  37. 2 2013-08-08 0
  38. 2 2013-08-09 0
  39. 2 2013-08-10 0
  40. 2 2013-08-11 0
  41. 2 2013-08-12 0
  42. 2 2013-08-13 0
  43. 2 2013-08-14 0
  44. 2 2013-08-15 0
  45. 2 2013-08-16 0
  46. 2 2013-08-17 39
  47. 2 2013-08-18 39
  48. 2 2013-08-19 39
  49. 2 2013-08-20 39
  50. 2 2013-08-21 39
  51. 2 2013-08-22 39
  52. 2 2013-08-23 39
  53. 2 2013-08-24 0
  54. 2 2013-08-25 0
  55. 2 2013-08-26 0
  56. 2 2013-08-27 0
  57. 2 2013-08-28 0
  58. 2 2013-08-29 0
  59. 2 2013-08-30 0
  60. 2 2013-08-31 0

如果有人对更好的数据结构有个好主意,我可以尝试实现.该数据库仍在建设中:-)

编辑:

  1. CREATE TABLE IF NOT EXISTS `pricesBookings` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,`baseId` int(11) NOT NULL,`bookingDate` date NOT NULL,`bookingId` int(11) NOT NULL,`price` decimal(10,2) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `baseId` (`baseId`,`bookingDate`)
  3. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
最佳答案
这应该给出正确的结果:

  1. select
  2. id,min(startDate) as startFreeDate,count(*) - (endDate is null) numFreeDays
  3. from (
  4. select
  5. pb1.id,pb1.bookingDate startDate,min(pb2.bookingDate) endDate
  6. from
  7. pricesBookings pb1 left join pricesBookings pb2
  8. on pb1.id=pb2.id
  9. and pb2.price>0
  10. and pb2.bookingDate>pb1.bookingDate
  11. where
  12. pb1.price=0
  13. group by
  14. pb1.id,pb1.bookingDate
  15. ) s
  16. group by id,endDate
  17. order by id,startDate

看它here.

如果您需要搜索所有免费插槽,例如14天,您可以添加HAVING:

  1. group by id,endDate
  2. having count(*) - (endDate is null) >= 14
  3. order by id,startDate

猜你在找的MySQL相关文章