search
HomeDatabaseMysql TutorialMysql日期类型大小比较---拉取给定时间段的记录_MySQL

bitsCN.com

我们知道,mysql里边,日期类型有很多表现形式,date, datetime,timestamp等类型。考虑这样一种场景:

按时间段拉取给定时间段的内容,这时,我们就得使用日期类型的比较了。

表结构:tablename_tbl

+-----------------+--------------+------+-----+-------------------+----------------+
| Field    |   Type |   Null |   Key |   Default |   Extra |
+-----------------+--------------+------+-----+-------------------+----------------+
| id    |   mediumint(8)   | NO    | PRI   | NULL    |   auto_increment |
| title    | varchar(40)    | NO    |    | NULL |    |
| content  | mediumtext    | NO    |    | NULL |    |
| addtime  | timestamp    | NO |    |   CURRENT_TIMESTAMP |    |

其中addtime为timestamp类型的,现在我们要拉去过去三小时内新增的记录,我们可以采取比较unix时间戳以及比较日期这两种方式实现;

首先看第一种:unix时间戳比较

Mysql内置函数:UNIX_TIMESTAMP()

若无参数调用,则默认返回一个 从 '1970-01-01 00:00:00' 到当前时刻的秒数(无符号整数)。若用date 来调用 unix_timestamp(),它会返回从 '1970-01-01 00:00:00' 到 date表示的时刻为止的秒数;date 可以是一个 date 字符串、一个 datetime字符串、一个 timestamp或一个当地时间的yymmdd 或yyymmdd格式的数字。

则sql语句可以这样写:

select id,title,content,addtime from tablename_tbl where UNIX_TIMESTAMP(addtime)>= UNIX_TIMESTAMP() - 10800 and UNIX_TIMESTAMP(addtime)

 

第二种方式:日期比较

首先看直接使用+-运算:

这种方式中,特别需要注意的是,一个时间日期值加/减一个值的含义。

select now();
+---------------------+
| now() |
+---------------------+
| 2013-03-15 13:08:45 |
+---------------------+

通过now函数,我们可以获取到当前的时间,然后再请看:

select now(),now()+1;
+---------------------+-----------------------+
| now() | now()+1 |
+---------------------+-----------------------+
| 2013-03-15 13:10:15 | 20130315131016.000000 |
+---------------------+-----------------------+

select now(),now()-1;
+---------------------+-----------------------+
| now() | now()-1 |
+---------------------+-----------------------+
| 2013-03-15 13:14:18 | 20130315131417.000000 |
+---------------------+-----------------------+

这两条语句执行后,第二列表示是在当前时刻加上/减去 一秒,这里要注意看第二列的表示形式:

20130315131016.000000  (yyyy mm dd HH MM ss.000000)即:在给now()加上或者减去一个值的时候,跟now()的结果的表示形式是不同的,我们再看:

select now(),now()-01;
+---------------------+-----------------------+
| now() | now()-01 |
+---------------------+-----------------------+
| 2013-03-15 13:15:05 | 20130315131504.000000 |
+---------------------+-----------------------+

select now(),now()+01;
+---------------------+-----------------------+
| now() | now()+01 |
+---------------------+-----------------------+
| 2013-03-15 13:15:11 | 20130315131512.000000 |
+---------------------+-----------------------+

看到这里,很奇怪是不是,怎么直接在数字前加0也可以执行?加减的难道不是秒数吗?(我之前就是这样认为的),执行的结果也是给now()加、减1秒;

select now(),now()+101;
+---------------------+-----------------------+
| now() | now()+101 |
+---------------------+-----------------------+
| 2013-03-15 13:17:14 | 20130315131815.000000 |
+---------------------+-----------------------+

select now(),now()-101;
+---------------------+-----------------------+
| now() | now()-101 |
+---------------------+-----------------------+
| 2013-03-15 13:17:22 | 20130315131621.000000 |
+---------------------+-----------------------+

我们这两条语句后的执行结果,通过对比两列,我们可以发现,分别是给now()的时刻加上1分钟、1秒钟, 减去1分钟、1秒钟;再看个例子

select now(),now()+0101;
+---------------------+-----------------------+
| now() | now()+0101 |
+---------------------+-----------------------+
| 2013-03-15 13:19:34 | 20130315132035.000000 |
+---------------------+-----------------------+

select now(),now()-0101;
+---------------------+-----------------------+
| now() | now()-0101 |
+---------------------+-----------------------+
| 2013-03-15 13:19:38 | 20130315131837.000000 |
+---------------------+-----------------------+

是不是跟奇怪了,这两条语句同样也是给当前时间加/减1分钟1秒钟。再看一个结合了年月日的例子:

select now(), now()+00010203040506;
+---------------------+-----------------------+
| now() | now()+00010203040506 |
+---------------------+-----------------------+
| 2013-03-15 13:21:50 | 20140518172656.000000 |
+---------------------+-----------------------+

select now(), now()-00010203040506;
+---------------------+-----------------------+
| now() | now()-00010203040506 |
+---------------------+-----------------------+
| 2013-03-15 13:21:54 | 20120112091648.000000 |
+---------------------+-----------------------+

看到这里,我们大概就能够明白了+-的含义了吧;上边两条语句是:给当前日期加减:1年2个月3天 4小时5分钟6秒钟。

所以,当我们在给now()+-一个时间的时候,其实应该这样理解的:

+1/+01:加1秒钟

+101/+0101:加1分钟1秒钟

+10101/+010101:加1小时1分钟1秒钟

+1010101/+01010101:加1天1分钟1秒钟

+101010101/+0101010101:加1月1天1分钟1秒钟

+1101010101/+010101010101:加1年1月1天1分钟1秒钟,这里要注意下,年这个部分可以是4位(高位没有的话会补零):00010101010101

(减也是类似的)

所以对于前边的问题:拉去过去三小时内新增的记录, 就可以这样写sql了:

select id,title,content,addtime from tablename_tbl where addtime >= now() - 30000 and addtime

 

另外还有一种方式就是使用mysql提供的:

date_add(向日期添加指定的时间间隔), DATE_ADD(date,INTERVAL expr type)

date 参数是合法的日期表达式。expr 参数是您希望添加的时间间隔。

Type 值
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH


date_sub(向日期减去指定的时间间隔), DATE_SUB(date,INTERVAL expr type) (使用方法同date_add类似)

sql可以这样写:

select id,title,content,addtime from tablename_tbl where addtime >= date_sub(now, INTERVAL 3 HOUR) AND addtime

(完)

bitsCN.com
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment