在MySQL中有一些常见的函数,总结如下:

1、当前日期

select curdate();
select current_date();

2、当前时间

select curtime();
select current_time();

3、当前日期和时间

select now();
select current_timestamp();

4、获取日期的年份、月份、日期

select year(current_date());
select month(current_date());
select day(current_date());

5、日期对应星期几

select dayname(current_date());

6、limit函数:用于限制查询结果返回的数量(注意:limit函数不支持SQL Server)

select * from 表名
limit i,n;

参数:

  i:为查询结果的索引值(默认从0开始)

  n:为查询结果返回的数量

7、查询组内前n条记录的函数

(1)MySQL

select column_name(s)
from table_name
limit i,n;

(2)SQL Server

select top numbers|percent
column_name(s)
from table_name;

(3)Oracle

select column_name(s)
from table_name
where rownum<=number;

8、时间差

(1)datediff函数:返回的差值是天数,不能定位到小时、分钟和秒。

-- 相差2天

select datediff('2018-03-22 09:00:00', '2018-03-20 07:00:00');

(2)timestampdiff函数:可以精确到天、小时、分钟和秒。对于比较的两个时间,小的在前面,大的在后面。

相差1天:select TIMESTAMPDIFF(DAY, '2018-03-20 23:59:00', '2018-03-22 00:00:00');

相差49小时:select TIMESTAMPDIFF(HOUR, '2018-03-20 09:00:00', '2018-03-22 10:00:00');

相差2049分钟:select TIMESTAMPDIFF(MINUTE, '2018-03-20 09:00:00', '2018-03-22 10:00:00');

相差176400秒:select TIMESTAMPDIFF(SECOND, '2018-03-20 09:00:00', '2018-03-22 10:00:00');