在 MySQL 中不含秒地使用时间数据类型?
你需要为此使用 DATE_FORMAT()。语法如下所示 -
SELECT DATE_FORMAT(yourColumnName,'%k:%i') as anyAliasName FROM yourTableName;
你可以使用 ‘%H:%i’ 来得到相同的结果。为了理解上述语法,让我们创建一个表。
创建表的查询如下所示 -
mysql> create table TimeDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> LastLoginTime time -> ); Query OK, 0 rows affected (0.56 sec)
现在你可以使用插入命令在表中插入一些记录。查询如下所示 -
mysql> insert into TimeDemo(LastLoginTime) values('09:30:35'); Query OK, 1 row affected (0.20 sec) mysql> insert into TimeDemo(LastLoginTime) values('10:45:30'); Query OK, 1 row affected (0.19 sec) mysql> insert into TimeDemo(LastLoginTime) values('13:33:58'); Query OK, 1 row affected (0.24 sec) mysql> insert into TimeDemo(LastLoginTime) values('15:45:31'); Query OK, 1 row affected (0.21 sec) mysql> insert into TimeDemo(LastLoginTime) values('16:40:36'); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录。查询如下所示 -
mysql> select *from TimeDemo;
以下是输出 -
+----+---------------+ | Id | LastLoginTime | +----+---------------+ | 1 | 09:30:35 | | 2 | 10:45:30 | | 3 | 13:33:58 | | 4 | 15:45:31 | | 5 | 16:40:36 | +----+---------------+ 5 rows in set (0.00 sec)
以下是得到不含秒的时间的查询。查询如下所示 -
mysql> select DATE_FORMAT(LastLoginTime,'%k:%i') as `Time` from TimeDemo;
以下是输出 -
+-------+ | Time | +-------+ | 9:30 | | 10:45 | | 13:33 | | 15:45 | | 16:40 | +-------+ 5 rows in set (0.00 sec)
你可以更改格式说明符比如 %H:%i 以得到不含秒的相同结果。查询如下所示 -
mysql> select DATE_FORMAT(LastLoginTime,' %H:%i') as `Time` from TimeDemo;
以下是输出 -
+--------+ | Time | +--------+ | 09:30 | | 10:45 | | 13:33 | | 15:45 | | 16:40 | +--------+ 5 rows in set (0.00 sec)
广告