mysql 日期截止,MySQL:IN子句的开始和结束日期之间的日期?

I have list of dates in the format YYYY-MM, and I have a table full of records with a starts_at and ends_at column.

I want to find all records for which any given date in the passed-in list is within the starts_at and ends_at range.

So, given 2011-01, 2011-05, 2011-10, I want:

| id | starts_at | ends_at | title |

| 3 | 2010-12-05 00:00:00 | 2011-02-02 00:00:00 | something cool |

| 4 | 2011-03-14 00:00:00 | 2011-05-01 00:00:00 | something else really cool |

| 5 | 2011-10-31 00:00:00 | 2012-12-23 00:00:00 | argh! end of the world! not cool! |

... while these records would be omitted:

| id | starts_at | ends_at | title |

| 6 | 2010-10-05 00:00:00 | 2010-12-02 00:00:00 | something uncool |

| 7 | 2011-03-14 00:00:00 | 2011-04-31 00:00:00 | something else really uncool |

| 8 | 2011-12-23 00:00:00 | 2013-01-01 00:00:00 | yay! we're still alive! cool! |

How would I write this WHERE condition in SQL?

Clarification: I'm looking for a solution in pure SQL (I'm working with a stored procedure, so dynamic injection through some other language like PHP isn't really possible, so far as I know), and the list of dates is being passed in to the query as a string (HTML form input). I would love to break it down into sequential BETWEEN statements if I could do that programmatically in SQL, but I've no clue how to do that.

Basically, I need a way to express the following logic in pure SQL:

$months = explode(',', '2011-01,2011-05,2011-10');

$q = "SELECT records.* FROM records WHERE";

foreach($months as $month) {

$q .= " '$month' BETWEEN records.starts_at AND records.ends_at OR";

}

$q = substr($q, 0, -3) . ';';

解决方案SELECT id, starts_at, ends_at, title

FROM yourtable

WHERE '2011-01-01' BETWEEN starts_at AND ends_at

OR '2011-05-01' BETWEEN starts_at AND ends_at

OR '2011-10-01' BETWEEN starts_at AND ends_at

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值