简体   繁体   English

找出mysql中两个日期范围之间重叠的天数

[英]Find out the number of days overlapping between two date ranges in mysql

I have a table with a date range.我有一个带有日期范围的表格。 I would like to find out if it overlaps another range and calculate the number of days overlapped.我想知道它是否与另一个范围重叠并计算重叠的天数。

Trying to do it in just mysql without going through loops in PHP which is the front end language.尝试仅在 mysql 中执行此操作,而无需在前端语言 PHP 中进行循环。

id | start_date | end_date
1  | 2019-01-02 | 2019-01-07
2  | 2019-01-03 | 2019-01-03
3  | 2019-01-06 | 2019-01-09

Date Range start = 2019-01-04 , Date range end = 2019-01-07日期范围start = 2019-01-04 ,日期范围end = 2019-01-07

With the dates being in the format YYYY-MM-DD日期format YYYY-MM-DD

Would like the end result being :希望最终结果是:

id | start_date | end_date    | total_days
1  | 2019-01-02 | 2019-01-07  | 4
2  | 2019-01-03 | 2019-01-03  | 0
3  | 2019-01-05 | 2019-01-09  | 3

Try to use MySQL DATEDIFF() function:尝试使用 MySQL DATEDIFF() 函数:

MySQL DATEDIFF() returns the number of days between two dates or datetimes. MySQL DATEDIFF() 返回两个日期或日期时间之间的天数。 This function only calculates the date portion from each expression.此函数仅计算每个表达式的日期部分。

DATEDIFF(expr1,expr2);

Click here to find examples 单击此处查找示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM