TIMESTAMPDIFF(interval,datetime_expr1,datetime_expr2)
其他:
QUARTER - 季度
WEEK - 星期
FRAC_SECOND - 毫秒
#建表
DROP TABLE IF EXISTS tb_user_video_log;
CREATE TABLE tb_user_video_log (
start_time DATETIME COMMENT '开始观看时间',
end_time DATETIME COMMENT '结束观看时间'
) CHARACTER SET utf8 COLLATE utf8_bin;
# 插入数据
INSERT INTO tb_user_video_log(start_time, end_time) VALUES
('2021-10-01 10:00:00', '2022-10-01 10:00:00'), # 年
('2021-10-01 11:00:00', '2021-11-01 11:00:00'), # 月
('2021-10-01 11:00:00', '2021-10-02 11:00:00'), # 日
('2021-09-01 11:00:00', '2021-09-01 10:00:00'), # 小时
('2021-09-01 10:01:00', '2021-09-01 10:00:00'), # 分钟
('2021-10-01 10:00:00', '2021-10-01 10:00:30'); # 秒
SELECT * FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(YEAR,start_time,end_time) FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(MONTH,start_time,end_time) FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(DAY,start_time,end_time) FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(HOUR,start_time,end_time) FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(MINUTE,start_time,end_time) FROM tb_user_video_log;
SELECT TIMESTAMPDIFF(SECOND,start_time,end_time) FROM tb_user_video_log;