时间查询-查询一列大于另一列

时间:2019-02-12 10:18:47

标签: mysql sql datetime

我正在尝试运行一个查询,该查询显示一列日期/时间与另一列日期/时间之间的延迟。 理想情况下,我希望能够指定比5小时更长的时间。

我希望能够显示结果,例如:

Select * from table
where column A is greater than column B

或者最好是where column A is greater than column B by 5 hours

4 个答案:

答案 0 :(得分:5)

使用TIMESTAMPDIFF

  Select * from table
    where TIMESTAMPDIFF(HOUR, start_time, end_time)>=5

答案 1 :(得分:3)

在MySQL中,您可以这样做:

where A > B

然后:

where A > B + interval 5 hour

我建议您习惯这种形式的比较,而不是根据差异进行思考。尽管在这种情况下可能没有什么区别,但是如果B是一个常量,则可以利用A上的索引。

答案 2 :(得分:0)

Select * from table
where (column A - column B) > 5/24

答案 3 :(得分:0)

日期算术以毫秒为单位。

Option Explicit

Public Sub CheckIfDataExists()
    Dim wsSearch As Worksheet
    Set wsSearch = ThisWorkbook.Worksheets("Tabelle1")

    Dim SearchRange As Range
    Set SearchRange = wsSearch.Range("A1", wsSearch.Cells(wsSearch.Rows.Count, "A").End(xlUp))

    Dim SearchData() As Variant 'data array
    SearchData = ThisWorkbook.Worksheets("Tabelle2").Range("C5:G8").Value

    Dim FoundData() As Variant

    'remember first find to prevent endless loop
    Dim FirstFoundAt As Range
    Set FirstFoundAt = SearchRange.Find(What:=SearchData(1, 1), After:=SearchRange.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

    If Not FirstFoundAt Is Nothing Then
        Dim FoundAt As Range
        Set FoundAt = FirstFoundAt
        Do
            Set FoundAt = SearchRange.Find(What:=SearchData(1, 1), After:=FoundAt, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
            If Not FoundAt Is Nothing Then
                FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Select
                FoundData = FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Value
                If AreArraysEqual(SearchData, FoundData) Then
                    MsgBox "data found at " & FoundAt.Resize(UBound(SearchData, 1), UBound(SearchData, 2)).Address
                    Exit Sub
                End If
            End If
        Loop Until FoundAt Is Nothing Or FirstFoundAt.Row >= FoundAt.Row
    End If

    MsgBox "data not found"
End Sub

Private Function AreArraysEqual(Arr1 As Variant, Arr2 As Variant) As Boolean
    Dim iRow As Long, iCol As Long

    'default
    AreArraysEqual = True

    For iRow = LBound(Arr1, 1) To UBound(Arr1, 1)
        For iCol = LBound(Arr1, 2) To UBound(Arr1, 2)
            If Arr1(iRow, iCol) <> Arr2(iRow, iCol) Then
                AreArraysEqual = False
                Exit Function
            End If
        Next iCol
    Next iRow
End Function

减去日期字段将产生毫秒。因此,将毫秒除以1000 * 60 * 60可得出经过的小时数。