MySQL 如何声明 datetime 变量?

mysqlmysqli database

要声明 datetime 变量,您需要使用 SET 命令使用用户定义变量。语法如下 −

SET @anyVariableName=’yourdatetimeValue’;

为了理解上述语法,让我们创建一个表。创建表的查询如下 −

mysql> create table datetimeVariables
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> ArrivalDatetime datetime,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.78 sec)

使用 insert 命令在表中插入一些记录。插入记录的查询如下 −

mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('John','2011-01-31 13:45:20');
Query OK, 1 row affected (0.53 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Sam','2012-04-25 15:30:25');
Query OK, 1 row affected (0.18 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Larry','2013-10-04 16:40:30');
Query OK, 1 row affected (0.10 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Bob','2014-05-15 10:30:25');
Query OK, 1 row affected (0.33 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('Mike','2017-08-13 11:30:25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into datetimeVariables(Name,ArrivalDatetime) values('David','2018-04-25 09:30:25');
Query OK, 1 row affected (0.20 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from datetimeVariables;

以下是输出 −

+----+-------+---------------------+
| Id | Name  | ArrivalDatetime     |
+----+-------+---------------------+
|  1 | John  | 2011-01-31 13:45:20 |
|  2 | Sam   | 2012-04-25 15:30:25 |
|  3 | Larry | 2013-10-04 16:40:30 |
|  4 | Bob   | 2014-05-15 10:30:25 |
|  5 | Mike  | 2017-08-13 11:30:25 |
|  6 | David | 2018-04-25 09:30:25 |
+----+-------+---------------------+
6 rows in set (0.00 sec)

以下是使用 SET 命令声明 datetime 变量的查询。查询如下 −

mysql> set @greaterThan2011Datetime='2012-04-25 15:30:25';
Query OK, 0 rows affected (0.00 sec)

以下是在选择查询中使用变量。查询如下 −

mysql> select *from datetimeVariables
   -> where ArrivalDatetime> = @greaterThan2011Datetime;

以下是输出 −

+----+-------+---------------------+
| Id | Name  | ArrivalDatetime     |
+----+-------+---------------------+
|  2 | Sam   | 2012-04-25 15:30:25 |
|  3 | Larry | 2013-10-04 16:40:30 |
|  4 | Bob   | 2014-05-15 10:30:25 |
|  5 | Mike  | 2017-08-13 11:30:25 |
|  6 | David | 2018-04-25 09:30:25 |
+----+-------+---------------------+
5 rows in set (0.00 sec)

相关文章