---
title: "mysql 实现相邻两条数据日期相减"
author: "bugyun"
date: "2018-12-30T14:27:45Z"
tags: []
categories: ["编程语言"]
slug: "mysql"
draft: false
lastmod: "2018-12-30T14:27:45Z"
id: 2435908
url: "https://bugyun.iteye.com/blog/2435908"
---

**参考：https://blog.csdn.net/yjgithub/article/details/75433345**

 

**功能：获取某一天的创建用户时间间隔**

 

 

**1. 表结构数据如下**

![](http://dl2.iteye.com/upload/attachment/0131/3079/63b6a1e2-4b67-3138-97b8-2de34fbfff26.png)  
 

 

**2. 查询结果如下**

![](http://dl2.iteye.com/upload/attachment/0131/3081/0bba0546-4950-3552-a97f-9ee384efe82c.png)  
 

 

**3. SQL语句如下**

 

```
SELECT
	two.id,
	two.user_name userName,
	two.create_time createTime,
	two.currentSecond,
	two.previousSecond,
	IF (two.previousSecond = 0, 0, two.currentSecond - two.previousSecond) intervalSecond
FROM
	(
		SELECT
			one.id,
			one.user_name,
			one.create_time,
			time_to_sec(one.create_time) currentSecond,
			@one.createTime AS previousSecond,
			@one.createTime := time_to_sec(one.create_time)
		FROM
			t_user_base one,
			(SELECT @one.createTime := 0) tmp
		ORDER BY
			one.create_time
	) two
```