MySQL选择日期等于今天并返回相同日期的结果?
要获取今天的日期,请使用内置函数CURDATE()
。该CURDATE()
只给出当前日期不是时间。这样,要获取当天的记录,您可以尝试以下语法-
select yourColumnName1,yourColumnName2,......,yourColumnNameN,DATE_FORMAT(yourDateColumnName, '%Y-%m-%d') from yourTableName WHERE DATE(yourDateColumnName) = CURDATE();
为了理解上述概念,让我们创建一个表。创建表的查询如下。这些列之一将具有datetime数据类型以显示日期-
mysql> create table GmailSignIn −> ( −> UserId int, −> UserName varchar(200), −> DateOfSignIn datetime −> );
现在,您可以借助insert命令将一些记录插入表中。我们还设置了当前日期,即2018-12-06。
查询如下-
mysql> insert into GmailSignIn values(222111,'John',now()); mysql> insert into GmailSignIn values(333222,'Johnson',curdate()); mysql> insert into GmailSignIn values(444333,'Carol',date_add(curdate(),interval 1 day)); mysql> insert into GmailSignIn values(555444,'David',date_add(curdate(),interval -1 day));
在select语句的帮助下显示表中的所有记录。查询如下-
mysql> select *from GmailSignIn;
以下是输出-
+--------+----------+---------------------+ | UserId | UserName | DateOfSignIn | +--------+----------+---------------------+ | 222111 | John | 2018-12-06 19:13:30 | | 333222 | Johnson | 2018-12-06 00:00:00 | | 444333 | Carol | 2018-12-07 00:00:00 | | 555444 | David | 2018-12-05 00:00:00 | +--------+----------+---------------------+ 4 rows in set (0.00 sec)
这是查询以选择等于今天的日期并显示同一日期的记录-
mysql> select UserId,UserName,DateOfSignIn,DATE_FORMAT(DateOfSignIn, '%Y-%m-%d') from GmailSignIn −> where date(DateOfSignIn) = curdate();
以下是输出-
+--------+----------+---------------------+---------------------------------------+ | UserId | UserName | DateOfSignIn | DATE_FORMAT(DateOfSignIn, '%Y-%m-%d') | +--------+----------+---------------------+---------------------------------------+ | 222111 | John | 2018-12-06 19:13:30 | 2018-12-06 | | 333222 | Johnson | 2018-12-06 00:00:00 | 2018-12-06 | +--------+----------+---------------------+---------------------------------------+ 2 rows in set (0.00 sec)