如何在一个 MySQL 查询中选择时间戳的一部分?
要在一个查询中选择时间戳的一部分,你需要使用 YEAR() 函数。以下是 MySQL 中的语法。
select YEAR(yourTimestampColumnName) as anyAliasName from yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下 -
mysql> create table SelectPartOfTimestampDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ShippingTime TIMESTAMP -> ); Query OK, 0 rows affected (1.11 sec)
现在你可以使用 insert 命令在表中插入一些记录。查询如下 -
mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(now()); Query OK, 1 row affected (0.20 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -2 year)); Query OK, 1 row affected (0.17 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -3 year)); Query OK, 1 row affected (0.18 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -1 year)); Query OK, 1 row affected (0.18 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 1 year)); Query OK, 1 row affected (0.16 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 2 year)); Query OK, 1 row affected (0.48 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 3 year)); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录。查询如下 -
mysql> select *from SelectPartOfTimestampDemo;
以下是输出 -
+----+---------------------+ | Id | ShippingTime | +----+---------------------+ | 1 | 2019-02-08 15:03:27 | | 2 | 2017-02-08 15:03:50 | | 3 | 2016-02-08 15:04:03 | | 4 | 2018-02-08 15:04:06 | | 5 | 2020-02-08 15:04:10 | | 6 | 2021-02-08 15:04:24 | | 7 | 2022-02-08 15:04:30 | +----+---------------------+ 7 rows in set (0.00 sec)
以下是使用 YEAR() 函数选择时间戳的一部分的查询 -
mysql> select YEAR(ShippingTime) as PartOfTimeStamp from SelectPartOfTimestampDemo;
以下是输出 -
+-----------------+ | PartOfTimeStamp | +-----------------+ | 2019 | | 2017 | | 2016 | | 2018 | | 2020 | | 2021 | | 2022 | +-----------------+ 7 rows in set (0.00 sec)
广告