2017-07-11 13 views
1

我试着找到这个问题的解决方案,但是我发现的所有内容都要求稍微不同的问题,或者没有得到足够的答案。我有以下设置的表:使用Self-Join查找行之间的差异

fullvna 

    +--------------+-------------+------+-----+---------+----------------+ 
    | Field  | Type  | Null | Key | Default | Extra   | 
    +--------------+-------------+------+-----+---------+----------------+ 
    | startdate | date  | YES |  | NULL |    | 
    | starttime | time  | YES |  | NULL |    | 
    | id   | int(11)  | NO | PRI | NULL | auto_increment | 
    +--------------+-------------+------+-----+---------+----------------+ 

我想找到每对连续行之间的时间差,所以= 1减去ID的开始时间= 2(表中有序ID的开始时间按时间顺序排列)。我根据我查询过什么,我在这里找到:http://www.mysqltutorial.org/mysql-tips/mysql-compare-calculate-difference-successive-rows/

create table difference as SELECT 
       one.id, 
          one.starttime, 
          two.starttime, 
          (one.starttime - two.starttime) AS diff 
      FROM 
          fullvna one 
              INNER JOIN 
          fullvna two ON two.id = one.id + 1; 

我收到下面的打印输出,并且我不知道这意味着什么或者什么,我做错了:

ERROR 1064 (42000): You have an error in your SQL syntax; check the 
    manual that corresponds to your MySQL server version for the right 
    syntax to use near '  one.starttime, 
        two.starttime, 
        (one.starttime - two.starttime' at line 3 
+2

您应该使用[TIMEDIFF(表达式1,表达式2)(http://www.w3resource.com/mysql/date-and-time-functions/mysql-timediff-function.php) –

+0

更改该行基本上返回相同的错误。现在日期和时间被分成两个单独的列而不是一个日期时间值。那是为什么? – Caitlin

+0

没有意义。 \t [**如何创建最小,完整和可验证的示例**](http://stackoverflow.com/help/mcve) \t尝试在http://rextester.com中创建示例 –

回答

2

你有隐藏的字符显示为空格,但他们不是,他们造成的错误。从我的答案复制查询。而胡安建议,推荐使用的,而不是减去他们TIMEDIFF()功能:

CREATE TABLE difference AS 
SELECT one.id, 
     one.starttime AS starttime, 
     two.starttime AS endtime, 
     TIMEDIFF(one.starttime, two.starttime) AS diff 
FROM fullvna one 
INNER JOIN fullvna two ON two.id = one.id + 1; 

编辑作为xQbert提到的,你需要为starttime列使用不同的名称,所以我纠正了上面的查询相应。

+0

我需要创建一个表,因为我将在稍后对结果运行查询。运行此操作会产生与我以前收到的错误相同的错误。“ – Caitlin

+0

”错误1064(42000):您的SQL语法错误;请查看与您的MySQL服务器版本对应的手册,以在'one.starttime, two.starttime, TIMEDIFF(one.starttime ,two.st'at line 2“ – Caitlin

+0

check @xQbert comment。'one'是一个保留字 –

3
  • 不要使用别名one因为它是一个关键字选择一个不同的一个
  • 别名STARTIME为两列具有相同名称在create table将无法正常工作。
  • timeDiff测量(如在评论中提到的其他人)

CREATE TABLE difference as 
SELECT a1.id 
     , a1.starttime as OneStartTime 
     , a2.starttime as TwoStartTime 
     , TIMEDIFF(a1.starttime, a2.starttime) AS diff 
FROM fullvna a1 
INNER JOIN fullvna a2 
    ON a2.id = a1.id + 1; 
+1

看起来真正的问题是重复的列名称。这是一个工作[DEMO](http://rextester.com/FFCZ42748)别名'''',即使保留不会给出任何错误。 –

+2

Na真正的问题是非显示字符(除空格外),然后是列名。 – xQbert

+0

什么非显示字符?以及你如何看待它? –