SQL method for calculating timestamp difference

SQL method for calculating timestamp difference

SQL method for calculating timestamp difference

Overview

Sometimes we need to find certain records by time, for example: calculate the records one hour before the sales time.
Usually we can use MYSQL's timestampdiff function to do this, but this cannot use the index, and if the amount of data is large, it will cause slow queries.

Use code to calculate the time and then pass it to SQL

We can use JAVA code to calculate the time first, and then pass it to the SQL statement to avoid using MYSQL functions.

public long xxxx(long sellTimeFrom){
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date(sellTimeFrom));
    calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY) - 1);
    return calendar.getTime().getTime();
}

This will calculate the time one hour before the sale time. Then pass it into the SQL statement where you write the code snippet. In this way, if the sales time field has an index, the index can be used.

Thank you for reading, I hope it can help you, thank you for your support of this site!

You may also be interested in:
  • MySQL slow query pitfalls
  • Solving the abnormality of mysql datetime query
  • Why MySQL can ignore time zone issues when using timestamp?
  • Pitfalls and solutions encountered in MySQL timestamp comparison query

<<:  Problems and solutions of using TweenMax animation library in angular

>>:  js implements a simple method of encapsulating jQuery and a detailed explanation of chain operations

Recommend

mysql three tables connected to create a view

Three tables are connected. Field a of table A co...

Detailed steps for developing WeChat mini-programs using Typescript

We don't need to elaborate too much on the ad...

Solution to the error when calling yum in docker container

When executing yum in dockerfile or in the contai...

HTML page native VIDEO tag hides the download button function

When writing a web project, I encountered an intr...

How to implement Docker container self-start

Container auto-start Docker provides a restart po...

Example of adding attributes using style in html

Add inline styles to the required links: Copy code...

JavaScript implements simple calculator function

This article example shares the specific code of ...

Detailed steps for quick installation of openshift

The fastest way to experience the latest version ...

Mini Programs use Mini Program Cloud to implement WeChat payment functions

Table of contents 1. Open WeChat Pay 1.1 Affiliat...

JavaScript Document Object Model DOM

Table of contents 1. JavaScript can change all HT...

Implementation code of front-end HTML skin changing function

50 lines of code to change 5 skin colors, includi...

Analysis of the cause of docker error Exited (1) 4 minutes ago

Docker error 1. Check the cause docker logs nexus...