$a = 1950-05-01
$b = 1965-08-10
$c = 1990-12-30
$d = 1990-12-29
$e = 2012-09-03
Run Code Online (Sandbox Code Playgroud)
从按日期升序排序的mysql数据库中检索日期.
我需要一个mysql或PHP脚本来获得具有最大天差的两个CONSECUTIVE日期.
解释:脚本应该计算$ a和$ b,$ b和$ c,$ c和$ d,$ d和$ e,$ e和$ a之间的天数,然后以最大天差输出两个日期.
有没有办法用一个快速的mysql/php代码执行此操作,或者我应该使用以下脚本进行一些循环(在stackoverflow上的另一个问题上找到它)?
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
echo floor($datediff/(60*60*24));
Run Code Online (Sandbox Code Playgroud)
查询列出日期:
SELECT date AS count FROM table WHERE column1 = 'YES' AND data BETWEEN 1950-01-01 AND 2012-09-04
Run Code Online (Sandbox Code Playgroud)
Ker*_*mit 14
假设每个日期都有一个顺序id.看到它在行动.
架构
CREATE TABLE tbl (
id tinyint,
dt date);
INSERT INTO tbl VALUES
(1, '1950-05-01'),
(2, '1965-08-10'),
(3, '1990-12-30'),
(4, '1990-12-29'),
(5, '2012-09-03')
Run Code Online (Sandbox Code Playgroud)
询问
SELECT a.dt AS date1,
(SELECT dt FROM tbl WHERE id = a.id - 1) AS date2,
DATEDIFF(a.dt, b.dt) AS diff
FROM tbl a
LEFT JOIN tbl b ON b.id = a.id -1
GROUP BY a.id
ORDER BY diff DESC
LIMIT 1
Run Code Online (Sandbox Code Playgroud)
结果
| DATE1 | DATE2 | DIFF | -------------------------------------------------------------------------- | August, 10 1965 00:00:00-0700 | December, 30 1990 00:00:00-0800 | 9273 |
$array = array('1950-05-01', '1965-08-10', '1990-12-30', '1990-12-29', '2012-09-03');
$maxDiff = 0;
$maxStart = NULL;
$maxEnd = NULL;
for($i = 1; $i <= count($array); $i++) {
if(isset($array[$i])) {
$diff = (strtotime($array[$i]) - strtotime($array[$i-1])) / (60*60*24);
if($diff > $maxDiff) {
$maxDiff = $diff;
$maxStart = $array[$i-1];
$maxEnd = $array[$i];
}
}
}
echo "The maximum days difference is between $maxStart and $maxEnd, with a difference of $maxDiff days";
Run Code Online (Sandbox Code Playgroud)
结果
The maximum days difference is between 1965-08-10 and 1990-12-30, with a difference of 9273.0416666667 days
更新1
关于PHP解决方案,如果您的日期不是有序的,您可以在循环使用之前对数组进行排序sort($array);.