如果时差超过一小时,如何显示结果

时间:2019-07-30 06:16:11

标签: mysql

我想在时差超过一小时的地方显示结果。这是示例查询:

SELECT 
  locator_id,
  NAME,
  DATE,
  destination,
  time_leave,
  time_return,
  isOfficial 
FROM
  locator_table 

这是结果:

locator_id  name    date        destination  time_leave  time_return  isOfficial  
----------  ------  ----------  -----------  ----------  -----------  ------------
         1  ALEX    2019-07-31  FRANCE       09:40 AM    09:50 AM                0
         2  MARK    2019-07-30  GERMANY      11:00 AM    01:00 PM                1
         3  JOHN    2019-07-30  TAIWAN       11:15 AM    12:00 PM                1
         4  FOO     2019-07-31  KOREA        01:20 PM    02:30 PM                1
         5  BAR     2019-07-30  JAPAN        01:50 PM    02:00 PM                0

现在您可以看到locator_id 2 and 4是时差超过一个小时的时钟。这应该是结果:

locator_id  name    date        destination  time_leave  time_return  isOfficial  
----------  ------  ----------  -----------  ----------  -----------  ------------
         2  MARK    2019-07-30  GERMANY      11:00 AM    01:00 PM                1
         4  FOO     2019-07-31  KOREA        01:20 PM    02:30 PM                1

如何实现?

2 个答案:

答案 0 :(得分:1)

您可以使用MySQL的TIMEDIFF函数,它应该类似于:

+----------+----------+------+
|    Id    | EventsId | Year |
+----------+----------+------+
|  8980909 |       64 | 2018 |
|  8980910 |       64 | 2018 |
|  8980911 |       64 | 2018 |
| 12380912 |       76 | 2018 |
| 12380913 |       76 | 2018 |
| 12380914 |       76 | 2018 |
| 12380915 |       76 | 2018 |
| 32880916 |      124 | 2018 |
| 32880917 |      124 | 2018 |
| 32880918 |      124 | 2018 |
| 32880919 |      124 | 2018 |
| 32880920 |      124 | 2018 |
| 56080920 |      125 | 2019 |
| 56080921 |      125 | 2019 |
| 56080922 |      125 | 2019 |
| 56080923 |      125 | 2019 |
| 61480923 |      305 | 2018 |
| 61480924 |      305 | 2018 |
| 61480925 |      305 | 2018 |
| 78280925 |      555 | 2018 |
| 78280926 |      555 | 2018 |
| 78280927 |      555 | 2018 |
| 78280928 |      555 | 2018 |
+----------+----------+------+

Fiddle Demo

答案 1 :(得分:0)

如果time_leavetime_return列为TIME或DATETIME类型,则可以使用MySQL TIMEDIFF函数来计算差异,使用HOUR函数来从差异中提取小时部分,并相应地选择行。

此语句将达到目的:

SELECT 
  locator_id,
  NAME,
  DATE,
  destination,
  time_leave,
  time_return,
  isOfficial 
FROM
  locator_table 
WHERE 
  HOUR(TIMEDIFF(time_return, time_leave)) > 1

请注意,这仅适用于DATETIME或TIME类型的值。 如果值为VARCHAR或CHAR类型,则需要事先进行一些转换为TIME或DATETIME类型。