如何确定数据库列中的值之间的差异并返回最小的差异?

时间:2014-01-31 08:17:24

标签: mysql sql

我在MySQL中有一列DATETIME值,我希望返回列中任意两个值之间的最小差异;我不需要知道它们之间或之间的差异是什么值,仅仅是这两个值之间的差异。

我的表看起来与此类似。

id    | launch_date_time
----------------------------
1     | 2012-01-02 18:42:00
2     | 2012-04-05 07:23:50
 ...
x     | 2014-08-07 22:19:11

是否有人能够指出我构建此类查询的正确方向?

4 个答案:

答案 0 :(得分:1)

我的第一个想法是,如果您的表名是table,请执行此操作

select min( abs( datediff(t1.launch_date_time, t2.launch_date_time) ) )
  from table t1
     , table t2
 where t1.id <> t2.id

这取决于那些表的大小,上面是O(N ^ 2)解,在O(N * log N)中你可以通过排序来做到这一点,结果是连续元素的min

// pseudo code
list = fromDb();
sort(list);
min = list[1] - list[0];
for i in 2 to list.size()
    min = min( min, list[i] - list[i-1] )

答案 1 :(得分:0)

select id,FROM_UNIXTIME(launch_date_time) as uTime,max(FROM_UNIXTIME(launch_date_time)) as max from table;

 //do db stuff
  //set the lowest to highest possible number so first comparison it will become the lowest.

   $lowest = $result['max'];

// iterate through array to get each time
foreach ($result['uTime'] as $v)
{

 //iterate again to compare each time u got from first loop to each in this loop

   foreach ($result['uTime as $x)
   { 
 //subtract your first value from the current
        $diff = $v - $x;

 //if its lower then any previous, and its positive set the new lowest.
        if ($diff < $lowest and $diff > 0)
        {
           $lowest = $diff;
        }
   }
}
 echo $lowest;

没有测试过这个......

答案 2 :(得分:0)

尝试此查询 -

SELECT
  t1.launch_date_time, MIN(t2.launch_date_time) launch_date_time2
FROM launch t1
  JOIN launch t2
    ON t2.launch_date_time > t1.launch_date_time
GROUP BY
  t1.launch_date_time
ORDER BY
  DATE(MIN(t2.launch_date_time)) * 86400 + TIME_TO_SEC(TIME(MIN(t2.launch_date_time))) - DATE(t1.launch_date_time) * 86400 + TIME_TO_SEC(TIME(t1.launch_date_time))
LIMIT 1

答案 3 :(得分:0)

在单个语句中执行此操作的SQL方法(以天为单位的差异): -

SELECT MIN(DATEDIFF(Sub1.launch_date_time, Sub2.launch_date_time))
FROM
(
    SELECT id, launch_date_time, @aCnt1 := @aCnt1 + 1 AS SeqCnt
    FROM SomeTable
    CROSS JOIN
    (
        SELECT @aCnt1:=0
    ) Deriv1
    ORDER BY launch_date_time
) Sub1
INNER JOIN
(
    SELECT id, launch_date_time, @aCnt2 := @aCnt2 + 1 AS SeqCnt
    FROM SomeTable
    CROSS JOIN
    (
        SELECT @aCnt2:=1
    ) Deriv2
    ORDER BY launch_date_time
) Sub2
ON Sub1.SeqCnt = Sub2.SeqCnt

SQL小提琴: -

http://www.sqlfiddle.com/#!2/6dc399/1