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

JavaScript canvas text clock

This article example shares the specific code of ...

Detailed analysis of the MySQL slow log opening method and storage format

In development projects, we can monitor SQL with ...

Use Docker Compose to quickly deploy ELK (tested and effective)

Table of contents 1. Overview 1.1 Definition 1.2 ...

Better looking CSS custom styles (title h1 h2 h3)

Rendering Commonly used styles in Blog Garden /*T...

Compile CPP files using G++ in Ubuntu

When I used g++ to compile the cpp file for the f...

Tutorial on installing MySQL 8.0.11 under Linux

1. Go to the official website to download the ins...

Sample code for implementing history in vuex

I have recently been developing a visual operatio...

JavaScript array reduce() method syntax and example analysis

Preface The reduce() method receives a function a...

CSS3 realizes the mask barrage function

Recently I saw a barrage effect on B station call...

Linux uses join -a1 to merge two files

To merge the following two files, merge them toge...

MySQL initialization password operation under Mac

A simple record of the database startup problems ...

The use and difference between JavaScript pseudo-array and array

Pseudo-arrays and arrays In JavaScript, except fo...