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

Vue 2.0 Basics in Detail

Table of contents 1. Features 2. Examples 3. Opti...

Basic tutorial on controlling Turtlebot3 mobile robot with ROS

Chinese Tutorial https://www.ncnynl.com/category/...

Detailed example of changing Linux account password

Change personal account password If ordinary user...

HTML+CSS to achieve responsive card hover effect

Table of contents accomplish: Summarize: Not much...

Implementing a simple calculator with javascript

This article example shares the specific code of ...

CSS3 creates web animation to achieve bouncing ball effect

Basic preparation For this implementation, we nee...

Virtual Box tutorial diagram of duplicating virtual machines

After getting used to VM, switching to BOX is a l...

How to build pptpd service in Alibaba Cloud Ubuntu 16.04

1. To build a PPTP VPN, you need to open port 172...

Things You Don’t Know About the CSS ::before and ::after Pseudo-Elements

CSS has two pseudo-classes that are not commonly ...

Vue Page Stack Manager Details

Table of contents 2. Tried methods 2.1 keep-alive...

WeChat applet implements SMS login in action

Table of contents 1. Interface effect preview 2.u...

Apply provide and inject to refresh Vue page method

Table of contents Method 1: Call the function dir...